Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- diffs/pr_10092/09f36b6/diff.json +0 -0
- diffs/pr_10092/1e62c87/diff.json +39 -0
- diffs/pr_10092/4714412/diff.json +39 -0
- diffs/pr_10092/5af5e3f/diff.json +39 -0
- diffs/pr_10092/b381264/diff.json +39 -0
- diffs/pr_10092/ba98639/diff.json +0 -0
- diffs/pr_10092/cc6026c/diff.json +24 -0
- diffs/pr_10092/ece0e2b/diff.json +24 -0
- diffs/pr_10092/fc53089/diff.json +0 -0
- diffs/pr_10168/35caa19/diff.json +0 -0
- diffs/pr_10190/1d6b507/diff.json +6 -0
- diffs/pr_10190/20caa86/diff.json +9 -0
- diffs/pr_10190/89c4fc2/diff.json +112 -0
- diffs/pr_10190/93824a2/diff.json +40 -0
- diffs/pr_10190/9cae8cf/diff.json +41 -0
- diffs/pr_10190/e27aae9/diff.json +182 -0
- diffs/pr_10190/e2b7d7e/diff.json +6 -0
- diffs/pr_10193/abf1d0c/diff.json +6 -0
- diffs/pr_10206/0faf91f/diff.json +0 -0
- diffs/pr_10206/122ff42/diff.json +24 -0
- diffs/pr_10206/33fad37/diff.json +24 -0
- diffs/pr_10206/49029b5/diff.json +0 -0
- diffs/pr_10206/4c2d145/diff.json +39 -0
- diffs/pr_10206/8cff7e3/diff.json +108 -0
- diffs/pr_10206/9354823/diff.json +54 -0
- diffs/pr_10206/ae9a3da/diff.json +39 -0
- diffs/pr_10206/b822b6c/diff.json +69 -0
- diffs/pr_6712/2443034/diff.json +39 -0
- diffs/pr_6761/01907d5/diff.json +30 -0
- diffs/pr_6761/025f70c/diff.json +0 -0
- diffs/pr_6761/063d978/diff.json +0 -0
- diffs/pr_6761/0a5c5e1/diff.json +103 -0
- diffs/pr_6761/0f4535b/diff.json +8 -0
- diffs/pr_6761/130ce8e/diff.json +24 -0
- diffs/pr_6761/1429f81/diff.json +169 -0
- diffs/pr_6761/17044b1/diff.json +0 -0
- diffs/pr_6761/17648f3/diff.json +0 -0
- diffs/pr_6761/198a308/diff.json +39 -0
- diffs/pr_6761/26f7a10/diff.json +0 -0
- diffs/pr_6761/354314a/diff.json +0 -0
- diffs/pr_6761/3c471f9/diff.json +25 -0
- diffs/pr_6761/405eaa5/diff.json +40 -0
- diffs/pr_6761/4f12340/diff.json +0 -0
- diffs/pr_6761/535532c/diff.json +8 -0
- diffs/pr_6761/55dc858/diff.json +39 -0
- diffs/pr_6761/584db45/diff.json +86 -0
- diffs/pr_6761/59e573c/diff.json +71 -0
- diffs/pr_6761/5ec8b3f/diff.json +242 -0
- diffs/pr_6761/6241147/diff.json +187 -0
- diffs/pr_6761/6a01879/diff.json +0 -0
diffs/pr_10092/09f36b6/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_10092/1e62c87/diff.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "1e62c877b744eb163d0efc887f2d6bb808ba02a2",
|
| 3 |
+
"pr_number": 10092,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/types/storage/revenue_recovery_redis_operation.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::impl::RedisTokenManager",
|
| 10 |
+
"file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs",
|
| 11 |
+
"kind": "impl_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap<String, String> = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap<String, String> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,\n ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option<CardNetwork>,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then(|| last_external_attempt_at).flatten()\n )\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n\n \n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option<String>,\n is_hard_decline: &Option<bool>,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult<bool, errors::StorageError> {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option<PrimitiveDateTime>,\n ) -> CustomResult<bool, errors::StorageError> {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::<HashMap<String, String>>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option<PrimitiveDateTime>,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec<AccountUpdateHistoryRecord> = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenWithRetryInfo>, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}",
|
| 16 |
+
"after_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap<String, String> = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap<String, String> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,\n ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option<CardNetwork>,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then(|| last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option<String>,\n is_hard_decline: &Option<bool>,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult<bool, errors::StorageError> {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option<PrimitiveDateTime>,\n ) -> CustomResult<bool, errors::StorageError> {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::<HashMap<String, String>>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option<PrimitiveDateTime>,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec<AccountUpdateHistoryRecord> = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenWithRetryInfo>, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then(|| last_external_attempt_at).flatten()\n )\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n\n \n })\n .or_else(|| {",
|
| 19 |
+
"after": " .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then(|| last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "1e62c877b744eb163d0efc887f2d6bb808ba02a2"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::RedisTokenManager::function::upsert_payment_processor_token",
|
| 25 |
+
"file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs",
|
| 26 |
+
"kind": "function_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then(|| last_external_attempt_at).flatten()\n )\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n\n \n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }",
|
| 31 |
+
"after_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then(|| last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then(|| last_external_attempt_at).flatten()\n )\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n\n \n })\n .or_else(|| {",
|
| 34 |
+
"after": " .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then(|| last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "1e62c877b744eb163d0efc887f2d6bb808ba02a2"
|
| 37 |
+
}
|
| 38 |
+
]
|
| 39 |
+
}
|
diffs/pr_10092/4714412/diff.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "471441242afddd68b77f9ee93771261eb8dea3c4",
|
| 3 |
+
"pr_number": 10092,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/types/storage/revenue_recovery_redis_operation.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::impl::RedisTokenManager",
|
| 10 |
+
"file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs",
|
| 11 |
+
"kind": "impl_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap<String, String> = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap<String, String> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,\n ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option<CardNetwork>,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option<String>,\n is_hard_decline: &Option<bool>,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult<bool, errors::StorageError> {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option<PrimitiveDateTime>,\n ) -> CustomResult<bool, errors::StorageError> {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::<HashMap<String, String>>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option<PrimitiveDateTime>,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec<AccountUpdateHistoryRecord> = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenWithRetryInfo>, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}",
|
| 16 |
+
"after_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap<String, String> = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap<String, String> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,\n ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option<CardNetwork>,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option<String>,\n is_hard_decline: &Option<bool>,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult<bool, errors::StorageError> {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option<PrimitiveDateTime>,\n ) -> CustomResult<bool, errors::StorageError> {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::<HashMap<String, String>>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option<PrimitiveDateTime>,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec<AccountUpdateHistoryRecord> = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenWithRetryInfo>, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);",
|
| 19 |
+
"after": " .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "471441242afddd68b77f9ee93771261eb8dea3c4"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::RedisTokenManager::function::upsert_payment_processor_token",
|
| 25 |
+
"file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs",
|
| 26 |
+
"kind": "function_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }",
|
| 31 |
+
"after_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);",
|
| 34 |
+
"after": " .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "471441242afddd68b77f9ee93771261eb8dea3c4"
|
| 37 |
+
}
|
| 38 |
+
]
|
| 39 |
+
}
|
diffs/pr_10092/5af5e3f/diff.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "5af5e3f46946169387acaa9c218ce40885cd3803",
|
| 3 |
+
"pr_number": 10092,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/types/storage/revenue_recovery_redis_operation.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::impl::RedisTokenManager",
|
| 10 |
+
"file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs",
|
| 11 |
+
"kind": "impl_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap<String, String> = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap<String, String> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,\n ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option<CardNetwork>,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then(|| last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option<String>,\n is_hard_decline: &Option<bool>,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult<bool, errors::StorageError> {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option<PrimitiveDateTime>,\n ) -> CustomResult<bool, errors::StorageError> {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::<HashMap<String, String>>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option<PrimitiveDateTime>,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec<AccountUpdateHistoryRecord> = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenWithRetryInfo>, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}",
|
| 16 |
+
"after_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap<String, String> = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap<String, String> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,\n ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option<CardNetwork>,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option<String>,\n is_hard_decline: &Option<bool>,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult<bool, errors::StorageError> {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option<PrimitiveDateTime>,\n ) -> CustomResult<bool, errors::StorageError> {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::<HashMap<String, String>>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option<PrimitiveDateTime>,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec<AccountUpdateHistoryRecord> = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenWithRetryInfo>, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then(|| last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);",
|
| 19 |
+
"after": " .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "5af5e3f46946169387acaa9c218ce40885cd3803"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::RedisTokenManager::function::upsert_payment_processor_token",
|
| 25 |
+
"file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs",
|
| 26 |
+
"kind": "function_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then(|| last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }",
|
| 31 |
+
"after_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then(|| last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);",
|
| 34 |
+
"after": " .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "5af5e3f46946169387acaa9c218ce40885cd3803"
|
| 37 |
+
}
|
| 38 |
+
]
|
| 39 |
+
}
|
diffs/pr_10092/b381264/diff.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "b3812645619bba713f222fe390ec77e89192ecfb",
|
| 3 |
+
"pr_number": 10092,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/types/storage/revenue_recovery_redis_operation.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::impl::RedisTokenManager",
|
| 10 |
+
"file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs",
|
| 11 |
+
"kind": "impl_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap<String, String> = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap<String, String> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,\n ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option<CardNetwork>,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option<String>,\n is_hard_decline: &Option<bool>,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult<bool, errors::StorageError> {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option<PrimitiveDateTime>,\n ) -> CustomResult<bool, errors::StorageError> {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::<HashMap<String, String>>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option<PrimitiveDateTime>,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec<AccountUpdateHistoryRecord> = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenWithRetryInfo>, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}",
|
| 16 |
+
"after_code": "impl RedisTokenManager {\n fn get_connector_customer_lock_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:status\")\n }\n\n fn get_connector_customer_tokens_key(connector_customer_id: &str) -> String {\n format!(\"customer:{connector_customer_id}:tokens\")\n }\n\n /// Lock connector customer\n #[instrument(skip_all)]\n pub async fn lock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n payment_id: &id_type::GlobalPaymentId,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n let result: bool = match redis_conn\n .set_key_if_not_exists_with_expiry(\n &lock_key.into(),\n payment_id.get_string_repr(),\n Some(*seconds),\n )\n .await\n {\n Ok(resp) => resp == SetnxReply::KeySet,\n Err(error) => {\n tracing::error!(operation = \"lock_stream\", err = ?error);\n false\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n payment_id = payment_id.get_string_repr(),\n lock_acquired = %result,\n \"Connector customer lock attempt\"\n );\n\n Ok(result)\n }\n #[instrument(skip_all)]\n pub async fn update_connector_customer_lock_ttl(\n state: &SessionState,\n connector_customer_id: &str,\n exp_in_seconds: i64,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n let result: bool = redis_conn\n .set_expiry(&lock_key.clone().into(), exp_in_seconds)\n .await\n .map_or_else(\n |error| {\n tracing::error!(operation = \"update_lock_ttl\", err = ?error);\n false\n },\n |_| true,\n );\n\n if result {\n tracing::debug!(\n lock_key = %lock_key,\n new_ttl_in_seconds = exp_in_seconds,\n \"Redis key TTL updated successfully\"\n );\n } else {\n tracing::error!(\n lock_key = %lock_key,\n \"Failed to update TTL: key not found or error occurred\"\n );\n }\n\n Ok(())\n }\n\n /// Unlock connector customer status\n #[instrument(skip_all)]\n pub async fn unlock_connector_customer_status(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let lock_key = Self::get_connector_customer_lock_key(connector_customer_id);\n\n match redis_conn.delete_key(&lock_key.into()).await {\n Ok(DelReply::KeyDeleted) => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Connector customer unlocked\"\n );\n Ok(true)\n }\n Ok(DelReply::KeyNotDeleted) => {\n tracing::debug!(\"Tried to unlock a stream which is already unlocked\");\n Ok(false)\n }\n Err(err) => {\n tracing::error!(?err, \"Failed to delete lock key\");\n Ok(false)\n }\n }\n }\n\n /// Get all payment processor tokens for a connector customer\n #[instrument(skip_all)]\n pub async fn get_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenStatus>, errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n let get_hash_err =\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into());\n\n let payment_processor_tokens: HashMap<String, String> = redis_conn\n .get_hash_fields(&tokens_key.into())\n .await\n .change_context(get_hash_err)?;\n\n let payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus> =\n payment_processor_tokens\n .into_iter()\n .filter_map(|(token_id, token_data)| {\n match serde_json::from_str::<PaymentProcessorTokenStatus>(&token_data) {\n Ok(token_status) => Some((token_id, token_status)),\n Err(err) => {\n tracing::warn!(\n connector_customer_id = %connector_customer_id,\n token_id = %token_id,\n error = %err,\n \"Failed to deserialize token data, skipping\",\n );\n None\n }\n }\n })\n .collect();\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor tokens\",\n );\n\n Ok(payment_processor_token_info_map)\n }\n\n /// Update connector customer payment processor tokens or add if doesn't exist\n #[instrument(skip_all)]\n pub async fn update_or_add_connector_customer_payment_processor_tokens(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token_info_map: HashMap<String, PaymentProcessorTokenStatus>,\n ) -> CustomResult<(), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n let tokens_key = Self::get_connector_customer_tokens_key(connector_customer_id);\n\n // allocate capacity up-front to avoid rehashing\n let mut serialized_payment_processor_tokens: HashMap<String, String> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n // serialize all tokens, preserving explicit error handling and attachable diagnostics\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map\n {\n let serialized = serde_json::to_string(&payment_processor_token_status)\n .change_context(errors::StorageError::SerializationFailed)\n .attach_printable(\"Failed to serialize token status\")?;\n\n serialized_payment_processor_tokens.insert(payment_processor_token_id, serialized);\n }\n let seconds = &state.conf.revenue_recovery.redis_ttl_in_seconds;\n\n // Update or add tokens\n redis_conn\n .set_hash_fields(\n &tokens_key.into(),\n serialized_payment_processor_tokens,\n Some(*seconds),\n )\n .await\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::SetHashFieldFailed.into(),\n ))?;\n\n tracing::info!(\n connector_customer_id = %connector_customer_id,\n \"Successfully updated or added customer tokens\",\n );\n\n Ok(())\n }\n\n /// Get current date in `yyyy-mm-dd` format.\n pub fn get_current_date() -> String {\n let today = date_time::now().date();\n\n let (year, month, day) = (today.year(), today.month(), today.day());\n\n format!(\"{year:04}-{month:02}-{day:02}\",)\n }\n\n /// Normalize retry window to exactly `RETRY_WINDOW_DAYS` days (today to `RETRY_WINDOW_DAYS - 1` days ago).\n pub fn normalize_retry_window(\n payment_processor_token: &mut PaymentProcessorTokenStatus,\n today: Date,\n ) {\n let mut normalized_retry_history: HashMap<Date, i32> = HashMap::new();\n\n for days_ago in 0..RETRY_WINDOW_DAYS {\n let date = today - Duration::days(days_ago.into());\n\n payment_processor_token\n .daily_retry_history\n .get(&date)\n .map(|&retry_count| {\n normalized_retry_history.insert(date, retry_count);\n });\n }\n\n payment_processor_token.daily_retry_history = normalized_retry_history;\n }\n\n /// Get all payment processor tokens with retry information and wait times.\n pub fn get_tokens_with_retry_metadata(\n state: &SessionState,\n payment_processor_token_info_map: &HashMap<String, PaymentProcessorTokenStatus>,\n ) -> HashMap<String, PaymentProcessorTokenWithRetryInfo> {\n let today = OffsetDateTime::now_utc().date();\n let card_config = &state.conf.revenue_recovery.card_config;\n\n let mut result: HashMap<String, PaymentProcessorTokenWithRetryInfo> =\n HashMap::with_capacity(payment_processor_token_info_map.len());\n\n for (payment_processor_token_id, payment_processor_token_status) in\n payment_processor_token_info_map.iter()\n {\n let card_network = payment_processor_token_status\n .payment_processor_token_details\n .card_network\n .clone();\n\n // Calculate retry information.\n let retry_info = Self::payment_processor_token_retry_info(\n state,\n payment_processor_token_status,\n today,\n card_network.clone(),\n );\n\n // Determine the wait time (max of monthly and daily wait hours).\n let retry_wait_time_hours = retry_info\n .monthly_wait_hours\n .max(retry_info.daily_wait_hours);\n\n // Obtain network-specific limits and compute remaining monthly retries.\n let card_network_config = card_config.get_network_config(card_network);\n\n let monthly_retry_remaining = std::cmp::max(\n 0,\n card_network_config.max_retry_count_for_thirty_day\n - retry_info.total_30_day_retries,\n );\n\n // Build the per-token result struct.\n let token_with_retry_info = PaymentProcessorTokenWithRetryInfo {\n token_status: payment_processor_token_status.clone(),\n retry_wait_time_hours,\n monthly_retry_remaining,\n total_30_day_retries: retry_info.total_30_day_retries,\n };\n\n result.insert(payment_processor_token_id.clone(), token_with_retry_info);\n }\n tracing::debug!(\"Fetched payment processor tokens with retry metadata\",);\n\n result\n }\n\n /// Sum retries over exactly the last 30 days\n fn calculate_total_30_day_retries(token: &PaymentProcessorTokenStatus, today: Date) -> i32 {\n (0..RETRY_WINDOW_DAYS)\n .map(|i| {\n let date = today - Duration::days(i.into());\n token\n .daily_retry_history\n .get(&date)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT)\n })\n .sum()\n }\n\n /// Calculate wait hours\n fn calculate_wait_hours(target_date: Date, now: OffsetDateTime) -> i64 {\n let expiry_time = target_date.midnight().assume_utc();\n (expiry_time - now).whole_hours().max(0)\n }\n\n /// Calculate retry counts for exactly the last 30 days\n pub fn payment_processor_token_retry_info(\n state: &SessionState,\n token: &PaymentProcessorTokenStatus,\n today: Date,\n network_type: Option<CardNetwork>,\n ) -> TokenRetryInfo {\n let card_config = &state.conf.revenue_recovery.card_config;\n let card_network_config = card_config.get_network_config(network_type);\n\n let now = OffsetDateTime::now_utc();\n\n let total_30_day_retries = Self::calculate_total_30_day_retries(token, today);\n\n let monthly_wait_hours =\n if total_30_day_retries >= card_network_config.max_retry_count_for_thirty_day {\n let mut accumulated_retries = 0;\n\n // Iterate from most recent to oldest\n (0..RETRY_WINDOW_DAYS)\n .map(|days_ago| today - Duration::days(days_ago.into()))\n .find(|date| {\n let retries = token.daily_retry_history.get(date).copied().unwrap_or(0);\n accumulated_retries += retries;\n accumulated_retries >= card_network_config.max_retry_count_for_thirty_day\n })\n .map(|breach_date| {\n Self::calculate_wait_hours(breach_date + Duration::days(31), now)\n })\n .unwrap_or(0)\n } else {\n 0\n };\n\n let today_retries = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n\n let daily_wait_hours = if today_retries >= card_network_config.max_retries_per_day {\n Self::calculate_wait_hours(today + Duration::days(1), now)\n } else {\n 0\n };\n\n TokenRetryInfo {\n monthly_wait_hours,\n daily_wait_hours,\n total_30_day_retries,\n }\n }\n\n // Upsert payment processor token\n #[instrument(skip_all)]\n pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }\n\n // Update payment processor token error code with billing connector response\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_error_code_from_process_tracker(\n state: &SessionState,\n connector_customer_id: &str,\n error_code: &Option<String>,\n is_hard_decline: &Option<bool>,\n payment_processor_token_id: Option<&str>,\n ) -> CustomResult<bool, errors::StorageError> {\n let today = OffsetDateTime::now_utc().date();\n let updated_token = match payment_processor_token_id {\n Some(token_id) => {\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == token_id\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status\n .payment_processor_token_details\n .clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: *is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n })\n }\n None => None,\n };\n\n match updated_token {\n Some(mut token) => {\n Self::normalize_retry_window(&mut token, today);\n\n match token.error_code {\n None => token.daily_retry_history.clear(),\n Some(_) => {\n let current_count = token\n .daily_retry_history\n .get(&today)\n .copied()\n .unwrap_or(INITIAL_RETRY_COUNT);\n token.daily_retry_history.insert(today, current_count + 1);\n }\n }\n\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with error code\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"No Token found with token id to update error code\",\n );\n Ok(false)\n }\n }\n }\n\n // Update all payment processor token schedule time to None\n #[instrument(skip_all)]\n pub async fn update_payment_processor_tokens_schedule_time_to_none(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<(), errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let mut updated_tokens_map = HashMap::new();\n\n for (token_id, status) in tokens_map {\n let updated_status = PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: None,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n };\n updated_tokens_map.insert(token_id, updated_status);\n }\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n updated_tokens_map,\n )\n .await?;\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated all payment processor tokens schedule time to None\",\n );\n\n Ok(())\n }\n\n // Update payment processor token schedule time\n #[instrument(skip_all)]\n pub async fn update_payment_processor_token_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n schedule_time: Option<PrimitiveDateTime>,\n ) -> CustomResult<bool, errors::StorageError> {\n let updated_token =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?\n .values()\n .find(|status| {\n status\n .payment_processor_token_details\n .payment_processor_token\n == payment_processor_token\n })\n .map(|status| PaymentProcessorTokenStatus {\n payment_processor_token_details: status.payment_processor_token_details.clone(),\n inserted_by_attempt_id: status.inserted_by_attempt_id.clone(),\n error_code: status.error_code.clone(),\n daily_retry_history: status.daily_retry_history.clone(),\n scheduled_at: schedule_time,\n is_hard_decline: status.is_hard_decline,\n modified_at: Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n )),\n is_active: status.is_active,\n account_update_history: status.account_update_history.clone(),\n });\n\n match updated_token {\n Some(token) => {\n let mut tokens_map = HashMap::new();\n tokens_map.insert(\n token\n .payment_processor_token_details\n .payment_processor_token\n .clone(),\n token.clone(),\n );\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n tokens_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Updated payment processor tokens with schedule time\",\n );\n Ok(true)\n }\n None => {\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Payment processor tokens not found\",\n );\n Ok(false)\n }\n }\n }\n\n // Get payment processor token with schedule time\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_with_schedule_time(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let tokens =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let scheduled_token = tokens\n .values()\n .find(|status| status.scheduled_at.is_some())\n .cloned();\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Fetched payment processor token with schedule time\",\n );\n\n Ok(scheduled_token)\n }\n\n // Get payment processor token using token id\n #[instrument(skip_all)]\n pub async fn get_payment_processor_token_using_token_id(\n state: &SessionState,\n connector_customer_id: &str,\n payment_processor_token: &str,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n // Get all tokens for the customer\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let token_details = tokens_map.get(payment_processor_token).cloned();\n\n tracing::debug!(\n token_found = token_details.is_some(),\n customer_id = connector_customer_id,\n \"Fetched payment processor token & Checked existence \",\n );\n\n Ok(token_details)\n }\n\n // Check if all tokens are hard declined or no token found for the customer\n #[instrument(skip_all)]\n pub async fn are_all_tokens_hard_declined(\n state: &SessionState,\n connector_customer_id: &str,\n ) -> CustomResult<bool, errors::StorageError> {\n let tokens_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n let all_hard_declined = tokens_map\n .values()\n .all(|token| token.is_hard_decline.unwrap_or(false));\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n all_hard_declined,\n \"Checked if all tokens are hard declined or no token found for the customer\",\n );\n\n Ok(all_hard_declined)\n }\n\n // Get token based on retry type\n pub async fn get_token_based_on_retry_type(\n state: &SessionState,\n connector_customer_id: &str,\n retry_algorithm_type: RevenueRecoveryAlgorithmType,\n last_token_used: Option<&str>,\n ) -> CustomResult<Option<PaymentProcessorTokenStatus>, errors::StorageError> {\n let mut token = None;\n match retry_algorithm_type {\n RevenueRecoveryAlgorithmType::Monitoring => {\n logger::error!(\"Monitoring type found for Revenue Recovery retry payment\");\n }\n\n RevenueRecoveryAlgorithmType::Cascading => {\n token = match last_token_used {\n Some(token_id) => {\n Self::get_payment_processor_token_using_token_id(\n state,\n connector_customer_id,\n token_id,\n )\n .await?\n }\n None => None,\n };\n }\n\n RevenueRecoveryAlgorithmType::Smart => {\n token = Self::get_payment_processor_token_with_schedule_time(\n state,\n connector_customer_id,\n )\n .await?;\n }\n }\n\n let token = match token {\n Some(t) => {\n if t.is_hard_decline.unwrap_or(false) {\n // Update the schedule time to None for hard declined tokens\n\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"Token is hard declined, setting schedule time to None\"\n );\n\n Self::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &t.payment_processor_token_details.payment_processor_token,\n None,\n )\n .await?;\n\n None\n } else {\n Some(t)\n }\n }\n None => {\n logger::warn!(\n connector_customer_id = connector_customer_id,\n \"No token found for the customer\",\n );\n None\n }\n };\n\n Ok(token)\n }\n\n /// Get Redis key data for revenue recovery\n #[instrument(skip_all)]\n pub async fn get_redis_key_data_raw(\n state: &SessionState,\n connector_customer_id: &str,\n key_type: &RedisKeyType,\n ) -> CustomResult<(bool, i64, Option<serde_json::Value>), errors::StorageError> {\n let redis_conn =\n state\n .store\n .get_redis_conn()\n .change_context(errors::StorageError::RedisError(\n errors::RedisError::RedisConnectionError.into(),\n ))?;\n\n let redis_key = match key_type {\n RedisKeyType::Status => Self::get_connector_customer_lock_key(connector_customer_id),\n RedisKeyType::Tokens => Self::get_connector_customer_tokens_key(connector_customer_id),\n };\n\n // Get TTL\n let ttl = redis_conn\n .get_ttl(&redis_key.clone().into())\n .await\n .map_err(|error| {\n tracing::error!(operation = \"get_ttl\", err = ?error);\n errors::StorageError::RedisError(errors::RedisError::GetHashFieldFailed.into())\n })?;\n\n // Get data based on key type and determine existence\n let (key_exists, data) = match key_type {\n RedisKeyType::Status => match redis_conn.get_key::<String>(&redis_key.into()).await {\n Ok(status_value) => (true, serde_json::Value::String(status_value)),\n Err(error) => {\n tracing::error!(operation = \"get_status_key\", err = ?error);\n (\n false,\n serde_json::Value::String(format!(\n \"Error retrieving status key: {}\",\n error\n )),\n )\n }\n },\n RedisKeyType::Tokens => {\n match redis_conn\n .get_hash_fields::<HashMap<String, String>>(&redis_key.into())\n .await\n {\n Ok(hash_fields) => {\n let exists = !hash_fields.is_empty();\n let data = if exists {\n serde_json::to_value(hash_fields).unwrap_or(serde_json::Value::Null)\n } else {\n serde_json::Value::Object(serde_json::Map::new())\n };\n (exists, data)\n }\n Err(error) => {\n tracing::error!(operation = \"get_tokens_hash\", err = ?error);\n (false, serde_json::Value::Null)\n }\n }\n }\n };\n\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n key_type = ?key_type,\n exists = key_exists,\n ttl = ttl,\n \"Retrieved Redis key data\"\n );\n\n Ok((key_exists, ttl, Some(data)))\n }\n\n /// Update Redis token with comprehensive card data\n #[instrument(skip_all)]\n pub async fn update_redis_token_with_comprehensive_card_data(\n state: &SessionState,\n customer_id: &str,\n token: &str,\n card_data: &revenue_recovery_data_backfill::ComprehensiveCardData,\n cutoff_datetime: Option<PrimitiveDateTime>,\n ) -> CustomResult<(), errors::StorageError> {\n // Get existing token data\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n // Find the token to update\n let existing_token = token_map.get_mut(token).ok_or_else(|| {\n tracing::warn!(\n customer_id = customer_id,\n \"Token not found in parsed Redis data - may be corrupted or missing for \"\n );\n error_stack::Report::new(errors::StorageError::ValueNotFound(\n \"Token not found in Redis\".to_string(),\n ))\n })?;\n\n // Update the token details with new card data\n card_data.card_type.as_ref().map(|card_type| {\n existing_token.payment_processor_token_details.card_type = Some(card_type.clone())\n });\n\n card_data.card_exp_month.as_ref().map(|exp_month| {\n existing_token.payment_processor_token_details.expiry_month = Some(exp_month.clone())\n });\n\n card_data.card_exp_year.as_ref().map(|exp_year| {\n existing_token.payment_processor_token_details.expiry_year = Some(exp_year.clone())\n });\n\n card_data.card_network.as_ref().map(|card_network| {\n existing_token.payment_processor_token_details.card_network = Some(card_network.clone())\n });\n\n card_data.card_issuer.as_ref().map(|card_issuer| {\n existing_token.payment_processor_token_details.card_issuer = Some(card_issuer.clone())\n });\n\n // Update daily retry history if provided\n card_data\n .daily_retry_history\n .as_ref()\n .map(|retry_history| existing_token.daily_retry_history = retry_history.clone());\n\n // If cutoff_datetime is provided and existing scheduled_at < cutoff_datetime, set to None\n // If no scheduled_at value exists, leave it as None\n existing_token.scheduled_at = existing_token\n .scheduled_at\n .and_then(|existing_scheduled_at| {\n cutoff_datetime\n .map(|cutoff| {\n if existing_scheduled_at < cutoff {\n tracing::info!(\n customer_id = customer_id,\n existing_scheduled_at = %existing_scheduled_at,\n cutoff_datetime = %cutoff,\n \"Set scheduled_at to None because existing time is before cutoff time\"\n );\n None\n } else {\n Some(existing_scheduled_at)\n }\n })\n .unwrap_or(Some(existing_scheduled_at)) // No cutoff provided, keep existing value\n });\n\n existing_token.modified_at = Some(PrimitiveDateTime::new(\n OffsetDateTime::now_utc().date(),\n OffsetDateTime::now_utc().time(),\n ));\n\n // Update account_update_history if provided\n if let Some(history) = &card_data.account_update_history {\n // Convert api_models::AccountUpdateHistoryRecord to storage::AccountUpdateHistoryRecord\n let converted_history: Vec<AccountUpdateHistoryRecord> = history\n .iter()\n .map(|api_record| AccountUpdateHistoryRecord {\n old_token: api_record.old_token.clone(),\n new_token: api_record.new_token.clone(),\n updated_at: api_record.updated_at,\n old_token_info: api_record.old_token_info.clone(),\n new_token_info: api_record.new_token_info.clone(),\n })\n .collect();\n existing_token.account_update_history = Some(converted_history);\n }\n\n // Update is_active if provided\n card_data.is_active.map(|is_active| {\n existing_token.is_active = Some(is_active);\n });\n\n // Save the updated token map back to Redis\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n customer_id,\n token_map,\n )\n .await?;\n\n tracing::info!(\n customer_id = customer_id,\n \"Updated Redis token data with comprehensive card data using struct\"\n );\n\n Ok(())\n }\n pub async fn get_payment_processor_metadata_for_connector_customer(\n state: &SessionState,\n customer_id: &str,\n ) -> CustomResult<HashMap<String, PaymentProcessorTokenWithRetryInfo>, errors::StorageError>\n {\n let token_map =\n Self::get_connector_customer_payment_processor_tokens(state, customer_id).await?;\n\n let token_data = Self::get_tokens_with_retry_metadata(state, &token_map);\n\n Ok(token_data)\n }\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);",
|
| 19 |
+
"after": " .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "b3812645619bba713f222fe390ec77e89192ecfb"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs::RedisTokenManager::function::upsert_payment_processor_token",
|
| 25 |
+
"file": "crates/router/src/types/storage/revenue_recovery_redis_operation.rs",
|
| 26 |
+
"kind": "function_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }",
|
| 31 |
+
"after_code": "pub async fn upsert_payment_processor_token(\n state: &SessionState,\n connector_customer_id: &str,\n token_data: PaymentProcessorTokenStatus,\n ) -> CustomResult<bool, errors::StorageError> {\n let mut token_map =\n Self::get_connector_customer_payment_processor_tokens(state, connector_customer_id)\n .await?;\n\n let token_id = token_data\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let was_existing = token_map.contains_key(&token_id);\n\n let error_code = token_data.error_code.clone();\n\n let last_external_attempt_at = token_data.modified_at;\n\n let today = OffsetDateTime::now_utc().date();\n\n token_map\n .get_mut(&token_id)\n .map(|existing_token| {\n Self::normalize_retry_window(existing_token, today);\n\n for (date, &value) in &token_data.daily_retry_history {\n existing_token\n .daily_retry_history\n .entry(*date)\n .and_modify(|v| *v += value)\n .or_insert(value);\n }\n\n existing_token\n .modified_at\n .zip(last_external_attempt_at)\n .and_then(|(existing_token_modified_at, last_external_attempt_at)| {\n (last_external_attempt_at > existing_token_modified_at)\n .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);\n existing_token.error_code = error_code;\n existing_token.is_hard_decline = token_data.is_hard_decline;\n });\n })\n .or_else(|| {\n token_map.insert(token_id.clone(), token_data);\n None\n });\n\n Self::update_or_add_connector_customer_payment_processor_tokens(\n state,\n connector_customer_id,\n token_map,\n )\n .await?;\n tracing::debug!(\n connector_customer_id = connector_customer_id,\n \"Upsert payment processor tokens\",\n );\n\n Ok(!was_existing)\n }",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " .then_some(last_external_attempt_at)\n })\n .or_else(|| existing_token.modified_at.is_none().then_some(last_external_attempt_at).flatten())\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);",
|
| 34 |
+
"after": " .then_some(last_external_attempt_at)\n })\n .or_else(|| {\n existing_token\n .modified_at\n .is_none()\n .then_some(last_external_attempt_at)\n .flatten()\n })\n .map(|last_external_attempt_at| {\n existing_token.modified_at = Some(last_external_attempt_at);"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "b3812645619bba713f222fe390ec77e89192ecfb"
|
| 37 |
+
}
|
| 38 |
+
]
|
| 39 |
+
}
|
diffs/pr_10092/ba98639/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_10092/cc6026c/diff.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "cc6026c7b7fe06b5235d2f852def6d00db4b0454",
|
| 3 |
+
"pr_number": 10092,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/workflows/revenue_recovery.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::call_decider_for_payment_processor_tokens_select_closest_time",
|
| 10 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n for token_with_retry_info in processor_tokens.values() {\n process_token_for_retry(state, token_with_retry_info, payment_intent)\n .await?\n .map(|token_with_schedule_time| {\n tokens_with_schedule_time.push(token_with_schedule_time)\n });\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n \n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 16 |
+
"after_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n for token_with_retry_info in processor_tokens.values() {\n process_token_for_retry(state, token_with_retry_info, payment_intent)\n .await?\n .map(|token_with_schedule_time| {\n tokens_with_schedule_time.push(token_with_schedule_time)\n });\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n \n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)",
|
| 19 |
+
"after": ""
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "cc6026c7b7fe06b5235d2f852def6d00db4b0454"
|
| 22 |
+
}
|
| 23 |
+
]
|
| 24 |
+
}
|
diffs/pr_10092/ece0e2b/diff.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "ece0e2b94281f8fcc9460ca2ce12e7362add0a31",
|
| 3 |
+
"pr_number": 10092,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/workflows/revenue_recovery.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::call_decider_for_payment_processor_tokens_select_closest_time",
|
| 10 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n for token_with_retry_info in processor_tokens.values() {\n process_token_for_retry(state, token_with_retry_info, payment_intent)\n .await?\n .map(|token_with_schedule_time| {\n tokens_with_schedule_time.push(token_with_schedule_time)\n });\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false));\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 16 |
+
"after_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n for token_with_retry_info in processor_tokens.values() {\n process_token_for_retry(state, token_with_retry_info, payment_intent)\n .await?\n .map(|token_with_schedule_time| {\n tokens_with_schedule_time.push(token_with_schedule_time)\n });\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n \n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false));\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)",
|
| 19 |
+
"after": " let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n \n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "ece0e2b94281f8fcc9460ca2ce12e7362add0a31"
|
| 22 |
+
}
|
| 23 |
+
]
|
| 24 |
+
}
|
diffs/pr_10092/fc53089/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_10168/35caa19/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_10190/1d6b507/diff.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "1d6b5074aad5d06dd4de87e801b70f036ed3d7e8",
|
| 3 |
+
"pr_number": 10190,
|
| 4 |
+
"rust_files": [],
|
| 5 |
+
"diffs": []
|
| 6 |
+
}
|
diffs/pr_10190/20caa86/diff.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "20caa86e9ac0a287ad046e283a0d42a5c50f8e94",
|
| 3 |
+
"pr_number": 10190,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/openapi/src/openapi.rs",
|
| 6 |
+
"crates/openapi/src/openapi_v2.rs"
|
| 7 |
+
],
|
| 8 |
+
"diffs": []
|
| 9 |
+
}
|
diffs/pr_10190/89c4fc2/diff.json
ADDED
|
@@ -0,0 +1,112 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "89c4fc2c6cae9f7f7838cc6b4fdaca5635c192c9",
|
| 3 |
+
"pr_number": 10190,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/api_models/src/admin.rs",
|
| 6 |
+
"crates/common_enums/src/enums.rs",
|
| 7 |
+
"crates/diesel_models/src/business_profile.rs",
|
| 8 |
+
"crates/router/src/types/transformers.rs"
|
| 9 |
+
],
|
| 10 |
+
"diffs": [
|
| 11 |
+
{
|
| 12 |
+
"id": "crates/router/src/types/transformers.rs::impl::diesel_models::business_profile::ExternalVaultConnectorDetails",
|
| 13 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 14 |
+
"kind": "impl_item",
|
| 15 |
+
"status": "modified",
|
| 16 |
+
"code_changed": true,
|
| 17 |
+
"imports_changed": false,
|
| 18 |
+
"before_code": "impl ForeignFrom<api_models::admin::ExternalVaultConnectorDetails>\n for diesel_models::business_profile::ExternalVaultConnectorDetails\n{\n fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n }\n }\n}",
|
| 19 |
+
"after_code": "impl ForeignFrom<api_models::admin::ExternalVaultConnectorDetails>\n for diesel_models::business_profile::ExternalVaultConnectorDetails\n{\n fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }\n}",
|
| 20 |
+
"diff_span": {
|
| 21 |
+
"before": "",
|
| 22 |
+
"after": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }"
|
| 23 |
+
},
|
| 24 |
+
"commit_sha": "89c4fc2c6cae9f7f7838cc6b4fdaca5635c192c9"
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"id": "crates/diesel_models/src/business_profile.rs::struct::ExternalVaultConnectorDetails",
|
| 28 |
+
"file": "crates/diesel_models/src/business_profile.rs",
|
| 29 |
+
"kind": "struct_item",
|
| 30 |
+
"status": "modified",
|
| 31 |
+
"code_changed": true,
|
| 32 |
+
"imports_changed": false,
|
| 33 |
+
"before_code": "pub struct ExternalVaultConnectorDetails {\n pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId,\n pub vault_sdk: Option<VaultSdk>,\n}",
|
| 34 |
+
"after_code": "pub struct ExternalVaultConnectorDetails {\n pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId,\n pub vault_sdk: Option<VaultSdk>,\n pub vault_token_selector: Option<Vec<common_enums::VaultTokenField>>,\n}",
|
| 35 |
+
"diff_span": {
|
| 36 |
+
"before": "",
|
| 37 |
+
"after": " pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId,\n pub vault_sdk: Option<VaultSdk>,\n pub vault_token_selector: Option<Vec<common_enums::VaultTokenField>>,\n}"
|
| 38 |
+
},
|
| 39 |
+
"commit_sha": "89c4fc2c6cae9f7f7838cc6b4fdaca5635c192c9"
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"id": "crates/router/src/types/transformers.rs::api_models::admin::ExternalVaultConnectorDetails::function::foreign_from",
|
| 43 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 44 |
+
"kind": "function_item",
|
| 45 |
+
"status": "modified",
|
| 46 |
+
"code_changed": true,
|
| 47 |
+
"imports_changed": false,
|
| 48 |
+
"before_code": "fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n }\n }",
|
| 49 |
+
"after_code": "fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }",
|
| 50 |
+
"diff_span": {
|
| 51 |
+
"before": "",
|
| 52 |
+
"after": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }"
|
| 53 |
+
},
|
| 54 |
+
"commit_sha": "89c4fc2c6cae9f7f7838cc6b4fdaca5635c192c9"
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"id": "crates/router/src/types/transformers.rs::impl::api_models::admin::ExternalVaultConnectorDetails",
|
| 58 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 59 |
+
"kind": "impl_item",
|
| 60 |
+
"status": "modified",
|
| 61 |
+
"code_changed": true,
|
| 62 |
+
"imports_changed": false,
|
| 63 |
+
"before_code": "impl ForeignFrom<diesel_models::business_profile::ExternalVaultConnectorDetails>\n for api_models::admin::ExternalVaultConnectorDetails\n{\n fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n }\n }\n}",
|
| 64 |
+
"after_code": "impl ForeignFrom<diesel_models::business_profile::ExternalVaultConnectorDetails>\n for api_models::admin::ExternalVaultConnectorDetails\n{\n fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }\n}",
|
| 65 |
+
"diff_span": {
|
| 66 |
+
"before": "",
|
| 67 |
+
"after": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }"
|
| 68 |
+
},
|
| 69 |
+
"commit_sha": "89c4fc2c6cae9f7f7838cc6b4fdaca5635c192c9"
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"id": "crates/api_models/src/admin.rs::struct::ExternalVaultConnectorDetails",
|
| 73 |
+
"file": "crates/api_models/src/admin.rs",
|
| 74 |
+
"kind": "struct_item",
|
| 75 |
+
"status": "modified",
|
| 76 |
+
"code_changed": true,
|
| 77 |
+
"imports_changed": false,
|
| 78 |
+
"before_code": "pub struct ExternalVaultConnectorDetails {\n /// Merchant Connector id to be stored for vault connector\n #[schema(value_type = Option<String>)]\n pub vault_connector_id: id_type::MerchantConnectorAccountId,\n\n /// External vault to be used for storing payment method information\n #[schema(value_type = Option<VaultSdk>)]\n pub vault_sdk: Option<common_enums::VaultSdk>,\n}",
|
| 79 |
+
"after_code": "pub struct ExternalVaultConnectorDetails {\n /// Merchant Connector id to be stored for vault connector\n #[schema(value_type = Option<String>)]\n pub vault_connector_id: id_type::MerchantConnectorAccountId,\n\n /// External vault to be used for storing payment method information\n #[schema(value_type = Option<VaultSdk>)]\n pub vault_sdk: Option<common_enums::VaultSdk>,\n\n /// Fields to tokenization in vault\n #[schema(value_type = Option<Vec<VaultSdk>>)]\n pub vault_token_selector: Option<Vec<common_enums::VaultTokenField>>,\n}",
|
| 80 |
+
"diff_span": {
|
| 81 |
+
"before": "",
|
| 82 |
+
"after": " #[schema(value_type = Option<VaultSdk>)]\n pub vault_sdk: Option<common_enums::VaultSdk>,\n\n /// Fields to tokenization in vault\n #[schema(value_type = Option<Vec<VaultSdk>>)]\n pub vault_token_selector: Option<Vec<common_enums::VaultTokenField>>,\n}"
|
| 83 |
+
},
|
| 84 |
+
"commit_sha": "89c4fc2c6cae9f7f7838cc6b4fdaca5635c192c9"
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"id": "crates/router/src/types/transformers.rs::diesel_models::business_profile::ExternalVaultConnectorDetails::function::foreign_from",
|
| 88 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 89 |
+
"kind": "function_item",
|
| 90 |
+
"status": "modified",
|
| 91 |
+
"code_changed": true,
|
| 92 |
+
"imports_changed": false,
|
| 93 |
+
"before_code": "fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n }\n }",
|
| 94 |
+
"after_code": "fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }",
|
| 95 |
+
"diff_span": {
|
| 96 |
+
"before": "",
|
| 97 |
+
"after": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }"
|
| 98 |
+
},
|
| 99 |
+
"commit_sha": "89c4fc2c6cae9f7f7838cc6b4fdaca5635c192c9"
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"id": "crates/common_enums/src/enums.rs::enum::VaultTokenField",
|
| 103 |
+
"file": "crates/common_enums/src/enums.rs",
|
| 104 |
+
"kind": "enum_item",
|
| 105 |
+
"status": "added",
|
| 106 |
+
"before_code": null,
|
| 107 |
+
"after_code": "pub enum VaultTokenField {\n /// Card number\n CardNumber,\n /// Card cvc\n CardCvc,\n /// Card expiry year\n CardExpiryYear,\n /// Card expiry month\n CardExpiryMonth,\n /// Network token\n NetworkToken,\n /// Token expiry year\n TokenExpiryYear,\n /// Token expiry month\n TokenExpiryMonth,\n /// Token cryptogram\n TokenCryptogram,\n}",
|
| 108 |
+
"diff_span": null,
|
| 109 |
+
"commit_sha": "89c4fc2c6cae9f7f7838cc6b4fdaca5635c192c9"
|
| 110 |
+
}
|
| 111 |
+
]
|
| 112 |
+
}
|
diffs/pr_10190/93824a2/diff.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "93824a2e2f0ead90097c45119ef7e4fb740a61d7",
|
| 3 |
+
"pr_number": 10190,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/api_models/src/admin.rs",
|
| 6 |
+
"crates/common_enums/src/enums.rs"
|
| 7 |
+
],
|
| 8 |
+
"diffs": [
|
| 9 |
+
{
|
| 10 |
+
"id": "crates/common_enums/src/enums.rs::enum::VaultTokenType",
|
| 11 |
+
"file": "crates/common_enums/src/enums.rs",
|
| 12 |
+
"kind": "enum_item",
|
| 13 |
+
"status": "modified",
|
| 14 |
+
"code_changed": true,
|
| 15 |
+
"imports_changed": false,
|
| 16 |
+
"before_code": "pub enum VaultTokenType {\n /// Card number\n CardNumber,\n /// Card cvc\n CardCvc,\n /// Card expiry year\n CardExpiryYear,\n /// Card expiry month\n CardExpiryMonth,\n /// Network token\n NetworkToken,\n /// Token expiry year\n TokenExpiryYear,\n /// Token expiry month\n TokenExpiryMonth,\n /// Token cryptogram\n TokenCryptogram,\n}",
|
| 17 |
+
"after_code": "pub enum VaultTokenType {\n /// Card number\n CardNumber,\n /// Card cvc\n CardCvc,\n /// Card expiry year\n CardExpiryYear,\n /// Card expiry month\n CardExpiryMonth,\n /// Network token\n NetworkToken,\n /// Token expiry year\n NetworkTokenExpiryYear,\n /// Token expiry month\n NetworkTokenExpiryMonth,\n /// Token cryptogram\n NetworkTokenCryptogram,\n}",
|
| 18 |
+
"diff_span": {
|
| 19 |
+
"before": " NetworkToken,\n /// Token expiry year\n TokenExpiryYear,\n /// Token expiry month\n TokenExpiryMonth,\n /// Token cryptogram\n TokenCryptogram,\n}",
|
| 20 |
+
"after": " NetworkToken,\n /// Token expiry year\n NetworkTokenExpiryYear,\n /// Token expiry month\n NetworkTokenExpiryMonth,\n /// Token cryptogram\n NetworkTokenCryptogram,\n}"
|
| 21 |
+
},
|
| 22 |
+
"commit_sha": "93824a2e2f0ead90097c45119ef7e4fb740a61d7"
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"id": "crates/api_models/src/admin.rs::struct::VaultTokenField",
|
| 26 |
+
"file": "crates/api_models/src/admin.rs",
|
| 27 |
+
"kind": "struct_item",
|
| 28 |
+
"status": "modified",
|
| 29 |
+
"code_changed": true,
|
| 30 |
+
"imports_changed": false,
|
| 31 |
+
"before_code": "pub struct VaultTokenField {\n /// Type of field to be tokenized in\n #[schema(value_type = Option<Vec<VaultTokenType>>)]\n pub token_type: common_enums::VaultTokenType,\n}",
|
| 32 |
+
"after_code": "pub struct VaultTokenField {\n /// Type of field to be tokenized in\n #[schema(value_type = Option<VaultTokenType>)]\n pub token_type: common_enums::VaultTokenType,\n}",
|
| 33 |
+
"diff_span": {
|
| 34 |
+
"before": "pub struct VaultTokenField {\n /// Type of field to be tokenized in\n #[schema(value_type = Option<Vec<VaultTokenType>>)]\n pub token_type: common_enums::VaultTokenType,\n}",
|
| 35 |
+
"after": "pub struct VaultTokenField {\n /// Type of field to be tokenized in\n #[schema(value_type = Option<VaultTokenType>)]\n pub token_type: common_enums::VaultTokenType,\n}"
|
| 36 |
+
},
|
| 37 |
+
"commit_sha": "93824a2e2f0ead90097c45119ef7e4fb740a61d7"
|
| 38 |
+
}
|
| 39 |
+
]
|
| 40 |
+
}
|
diffs/pr_10190/9cae8cf/diff.json
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "9cae8cf9f8e27804474d84110306267a93bdecd9",
|
| 3 |
+
"pr_number": 10190,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/api_models/src/admin.rs",
|
| 6 |
+
"crates/openapi/src/openapi.rs",
|
| 7 |
+
"crates/openapi/src/openapi_v2.rs"
|
| 8 |
+
],
|
| 9 |
+
"diffs": [
|
| 10 |
+
{
|
| 11 |
+
"id": "crates/api_models/src/admin.rs::struct::ExternalVaultConnectorDetails",
|
| 12 |
+
"file": "crates/api_models/src/admin.rs",
|
| 13 |
+
"kind": "struct_item",
|
| 14 |
+
"status": "modified",
|
| 15 |
+
"code_changed": true,
|
| 16 |
+
"imports_changed": false,
|
| 17 |
+
"before_code": "pub struct ExternalVaultConnectorDetails {\n /// Merchant Connector id to be stored for vault connector\n #[schema(value_type = Option<String>)]\n pub vault_connector_id: id_type::MerchantConnectorAccountId,\n\n /// External vault to be used for storing payment method information\n #[schema(value_type = Option<VaultSdk>)]\n pub vault_sdk: Option<common_enums::VaultSdk>,\n\n /// Fields to tokenization in vault\n #[schema(value_type = Option<Vec<VaultTokenField>>)]\n pub vault_token_selector: Option<Vec<VaultTokenField>>,\n}",
|
| 18 |
+
"after_code": "pub struct ExternalVaultConnectorDetails {\n /// Merchant Connector id to be stored for vault connector\n #[schema(value_type = Option<String>)]\n pub vault_connector_id: id_type::MerchantConnectorAccountId,\n\n /// External vault to be used for storing payment method information\n #[schema(value_type = Option<VaultSdk>)]\n pub vault_sdk: Option<common_enums::VaultSdk>,\n\n /// Fields to tokenization in vault\n pub vault_token_selector: Option<Vec<VaultTokenField>>,\n}",
|
| 19 |
+
"diff_span": {
|
| 20 |
+
"before": "\n /// Fields to tokenization in vault\n #[schema(value_type = Option<Vec<VaultTokenField>>)]\n pub vault_token_selector: Option<Vec<VaultTokenField>>,\n}",
|
| 21 |
+
"after": ""
|
| 22 |
+
},
|
| 23 |
+
"commit_sha": "9cae8cf9f8e27804474d84110306267a93bdecd9"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"id": "crates/api_models/src/admin.rs::struct::VaultTokenField",
|
| 27 |
+
"file": "crates/api_models/src/admin.rs",
|
| 28 |
+
"kind": "struct_item",
|
| 29 |
+
"status": "modified",
|
| 30 |
+
"code_changed": true,
|
| 31 |
+
"imports_changed": false,
|
| 32 |
+
"before_code": "pub struct VaultTokenField {\n /// Type of field to be tokenized in\n pub token_type: common_enums::VaultTokenType,\n}",
|
| 33 |
+
"after_code": "pub struct VaultTokenField {\n /// Type of field to be tokenized in\n #[schema(value_type = Option<Vec<VaultTokenType>>)]\n pub token_type: common_enums::VaultTokenType,\n}",
|
| 34 |
+
"diff_span": {
|
| 35 |
+
"before": "",
|
| 36 |
+
"after": "pub struct VaultTokenField {\n /// Type of field to be tokenized in\n #[schema(value_type = Option<Vec<VaultTokenType>>)]\n pub token_type: common_enums::VaultTokenType,\n}"
|
| 37 |
+
},
|
| 38 |
+
"commit_sha": "9cae8cf9f8e27804474d84110306267a93bdecd9"
|
| 39 |
+
}
|
| 40 |
+
]
|
| 41 |
+
}
|
diffs/pr_10190/e27aae9/diff.json
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b",
|
| 3 |
+
"pr_number": 10190,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/api_models/src/admin.rs",
|
| 6 |
+
"crates/common_enums/src/enums.rs",
|
| 7 |
+
"crates/diesel_models/src/business_profile.rs",
|
| 8 |
+
"crates/router/src/types/transformers.rs"
|
| 9 |
+
],
|
| 10 |
+
"diffs": [
|
| 11 |
+
{
|
| 12 |
+
"id": "crates/router/src/types/transformers.rs::impl::diesel_models::business_profile::ExternalVaultConnectorDetails",
|
| 13 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 14 |
+
"kind": "impl_item",
|
| 15 |
+
"status": "modified",
|
| 16 |
+
"code_changed": true,
|
| 17 |
+
"imports_changed": false,
|
| 18 |
+
"before_code": "impl ForeignFrom<api_models::admin::ExternalVaultConnectorDetails>\n for diesel_models::business_profile::ExternalVaultConnectorDetails\n{\n fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }\n}",
|
| 19 |
+
"after_code": "impl ForeignFrom<api_models::admin::ExternalVaultConnectorDetails>\n for diesel_models::business_profile::ExternalVaultConnectorDetails\n{\n fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector.map(|vault_token_selector| {\n vault_token_selector\n .into_iter()\n .map(ForeignFrom::foreign_from)\n .collect()\n }),\n }\n }\n}",
|
| 20 |
+
"diff_span": {
|
| 21 |
+
"before": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }",
|
| 22 |
+
"after": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector.map(|vault_token_selector| {\n vault_token_selector\n .into_iter()\n .map(ForeignFrom::foreign_from)\n .collect()\n }),\n }\n }"
|
| 23 |
+
},
|
| 24 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"id": "crates/diesel_models/src/business_profile.rs::struct::ExternalVaultConnectorDetails",
|
| 28 |
+
"file": "crates/diesel_models/src/business_profile.rs",
|
| 29 |
+
"kind": "struct_item",
|
| 30 |
+
"status": "modified",
|
| 31 |
+
"code_changed": true,
|
| 32 |
+
"imports_changed": false,
|
| 33 |
+
"before_code": "pub struct ExternalVaultConnectorDetails {\n pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId,\n pub vault_sdk: Option<VaultSdk>,\n pub vault_token_selector: Option<Vec<common_enums::VaultTokenField>>,\n}",
|
| 34 |
+
"after_code": "pub struct ExternalVaultConnectorDetails {\n pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId,\n pub vault_sdk: Option<VaultSdk>,\n pub vault_token_selector: Option<Vec<VaultTokenField>>,\n}",
|
| 35 |
+
"diff_span": {
|
| 36 |
+
"before": " pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId,\n pub vault_sdk: Option<VaultSdk>,\n pub vault_token_selector: Option<Vec<common_enums::VaultTokenField>>,\n}",
|
| 37 |
+
"after": " pub vault_connector_id: common_utils::id_type::MerchantConnectorAccountId,\n pub vault_sdk: Option<VaultSdk>,\n pub vault_token_selector: Option<Vec<VaultTokenField>>,\n}"
|
| 38 |
+
},
|
| 39 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"id": "crates/router/src/types/transformers.rs::api_models::admin::ExternalVaultConnectorDetails::function::foreign_from",
|
| 43 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 44 |
+
"kind": "function_item",
|
| 45 |
+
"status": "modified",
|
| 46 |
+
"code_changed": true,
|
| 47 |
+
"imports_changed": false,
|
| 48 |
+
"before_code": "fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }",
|
| 49 |
+
"after_code": "fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector.map(|vault_token_selector| {\n vault_token_selector\n .into_iter()\n .map(ForeignFrom::foreign_from)\n .collect()\n }),\n }\n }",
|
| 50 |
+
"diff_span": {
|
| 51 |
+
"before": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }",
|
| 52 |
+
"after": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector.map(|vault_token_selector| {\n vault_token_selector\n .into_iter()\n .map(ForeignFrom::foreign_from)\n .collect()\n }),\n }\n }"
|
| 53 |
+
},
|
| 54 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 55 |
+
},
|
| 56 |
+
{
|
| 57 |
+
"id": "crates/router/src/types/transformers.rs::impl::api_models::admin::ExternalVaultConnectorDetails",
|
| 58 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 59 |
+
"kind": "impl_item",
|
| 60 |
+
"status": "modified",
|
| 61 |
+
"code_changed": true,
|
| 62 |
+
"imports_changed": false,
|
| 63 |
+
"before_code": "impl ForeignFrom<diesel_models::business_profile::ExternalVaultConnectorDetails>\n for api_models::admin::ExternalVaultConnectorDetails\n{\n fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }\n}",
|
| 64 |
+
"after_code": "impl ForeignFrom<diesel_models::business_profile::ExternalVaultConnectorDetails>\n for api_models::admin::ExternalVaultConnectorDetails\n{\n fn foreign_from(item: diesel_models::business_profile::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector.map(|vault_token_selector| {\n vault_token_selector\n .into_iter()\n .map(ForeignFrom::foreign_from)\n .collect()\n }),\n }\n }\n}",
|
| 65 |
+
"diff_span": {
|
| 66 |
+
"before": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }",
|
| 67 |
+
"after": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector.map(|vault_token_selector| {\n vault_token_selector\n .into_iter()\n .map(ForeignFrom::foreign_from)\n .collect()\n }),\n }\n }"
|
| 68 |
+
},
|
| 69 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 70 |
+
},
|
| 71 |
+
{
|
| 72 |
+
"id": "crates/api_models/src/admin.rs::struct::ExternalVaultConnectorDetails",
|
| 73 |
+
"file": "crates/api_models/src/admin.rs",
|
| 74 |
+
"kind": "struct_item",
|
| 75 |
+
"status": "modified",
|
| 76 |
+
"code_changed": true,
|
| 77 |
+
"imports_changed": false,
|
| 78 |
+
"before_code": "pub struct ExternalVaultConnectorDetails {\n /// Merchant Connector id to be stored for vault connector\n #[schema(value_type = Option<String>)]\n pub vault_connector_id: id_type::MerchantConnectorAccountId,\n\n /// External vault to be used for storing payment method information\n #[schema(value_type = Option<VaultSdk>)]\n pub vault_sdk: Option<common_enums::VaultSdk>,\n\n /// Fields to tokenization in vault\n #[schema(value_type = Option<Vec<VaultSdk>>)]\n pub vault_token_selector: Option<Vec<common_enums::VaultTokenField>>,\n}",
|
| 79 |
+
"after_code": "pub struct ExternalVaultConnectorDetails {\n /// Merchant Connector id to be stored for vault connector\n #[schema(value_type = Option<String>)]\n pub vault_connector_id: id_type::MerchantConnectorAccountId,\n\n /// External vault to be used for storing payment method information\n #[schema(value_type = Option<VaultSdk>)]\n pub vault_sdk: Option<common_enums::VaultSdk>,\n\n /// Fields to tokenization in vault\n #[schema(value_type = Option<Vec<VaultTokenField>>)]\n pub vault_token_selector: Option<Vec<VaultTokenField>>,\n}",
|
| 80 |
+
"diff_span": {
|
| 81 |
+
"before": "\n /// Fields to tokenization in vault\n #[schema(value_type = Option<Vec<VaultSdk>>)]\n pub vault_token_selector: Option<Vec<common_enums::VaultTokenField>>,\n}",
|
| 82 |
+
"after": "\n /// Fields to tokenization in vault\n #[schema(value_type = Option<Vec<VaultTokenField>>)]\n pub vault_token_selector: Option<Vec<VaultTokenField>>,\n}"
|
| 83 |
+
},
|
| 84 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 85 |
+
},
|
| 86 |
+
{
|
| 87 |
+
"id": "crates/router/src/types/transformers.rs::diesel_models::business_profile::ExternalVaultConnectorDetails::function::foreign_from",
|
| 88 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 89 |
+
"kind": "function_item",
|
| 90 |
+
"status": "modified",
|
| 91 |
+
"code_changed": true,
|
| 92 |
+
"imports_changed": false,
|
| 93 |
+
"before_code": "fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }",
|
| 94 |
+
"after_code": "fn foreign_from(item: api_models::admin::ExternalVaultConnectorDetails) -> Self {\n Self {\n vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector.map(|vault_token_selector| {\n vault_token_selector\n .into_iter()\n .map(ForeignFrom::foreign_from)\n .collect()\n }),\n }\n }",
|
| 95 |
+
"diff_span": {
|
| 96 |
+
"before": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector,\n }\n }",
|
| 97 |
+
"after": " vault_connector_id: item.vault_connector_id,\n vault_sdk: item.vault_sdk,\n vault_token_selector: item.vault_token_selector.map(|vault_token_selector| {\n vault_token_selector\n .into_iter()\n .map(ForeignFrom::foreign_from)\n .collect()\n }),\n }\n }"
|
| 98 |
+
},
|
| 99 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"id": "crates/diesel_models/src/business_profile.rs::struct::VaultTokenField",
|
| 103 |
+
"file": "crates/diesel_models/src/business_profile.rs",
|
| 104 |
+
"kind": "struct_item",
|
| 105 |
+
"status": "added",
|
| 106 |
+
"before_code": null,
|
| 107 |
+
"after_code": "pub struct VaultTokenField {\n pub token_type: common_enums::VaultTokenType,\n}",
|
| 108 |
+
"diff_span": null,
|
| 109 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"id": "crates/router/src/types/transformers.rs::impl::diesel_models::business_profile::VaultTokenField",
|
| 113 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 114 |
+
"kind": "impl_item",
|
| 115 |
+
"status": "added",
|
| 116 |
+
"before_code": null,
|
| 117 |
+
"after_code": "impl ForeignFrom<api_models::admin::VaultTokenField>\n for diesel_models::business_profile::VaultTokenField\n{\n fn foreign_from(item: api_models::admin::VaultTokenField) -> Self {\n Self {\n token_type: item.token_type,\n }\n }\n}",
|
| 118 |
+
"diff_span": null,
|
| 119 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"id": "crates/router/src/types/transformers.rs::api_models::admin::VaultTokenField::function::foreign_from",
|
| 123 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 124 |
+
"kind": "function_item",
|
| 125 |
+
"status": "added",
|
| 126 |
+
"before_code": null,
|
| 127 |
+
"after_code": "fn foreign_from(item: diesel_models::business_profile::VaultTokenField) -> Self {\n Self {\n token_type: item.token_type,\n }\n }",
|
| 128 |
+
"diff_span": null,
|
| 129 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"id": "crates/common_enums/src/enums.rs::enum::VaultTokenType",
|
| 133 |
+
"file": "crates/common_enums/src/enums.rs",
|
| 134 |
+
"kind": "enum_item",
|
| 135 |
+
"status": "added",
|
| 136 |
+
"before_code": null,
|
| 137 |
+
"after_code": "pub enum VaultTokenType {\n /// Card number\n CardNumber,\n /// Card cvc\n CardCvc,\n /// Card expiry year\n CardExpiryYear,\n /// Card expiry month\n CardExpiryMonth,\n /// Network token\n NetworkToken,\n /// Token expiry year\n TokenExpiryYear,\n /// Token expiry month\n TokenExpiryMonth,\n /// Token cryptogram\n TokenCryptogram,\n}",
|
| 138 |
+
"diff_span": null,
|
| 139 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"id": "crates/api_models/src/admin.rs::struct::VaultTokenField",
|
| 143 |
+
"file": "crates/api_models/src/admin.rs",
|
| 144 |
+
"kind": "struct_item",
|
| 145 |
+
"status": "added",
|
| 146 |
+
"before_code": null,
|
| 147 |
+
"after_code": "pub struct VaultTokenField {\n /// Type of field to be tokenized in\n pub token_type: common_enums::VaultTokenType,\n}",
|
| 148 |
+
"diff_span": null,
|
| 149 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"id": "crates/router/src/types/transformers.rs::impl::api_models::admin::VaultTokenField",
|
| 153 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 154 |
+
"kind": "impl_item",
|
| 155 |
+
"status": "added",
|
| 156 |
+
"before_code": null,
|
| 157 |
+
"after_code": "impl ForeignFrom<diesel_models::business_profile::VaultTokenField>\n for api_models::admin::VaultTokenField\n{\n fn foreign_from(item: diesel_models::business_profile::VaultTokenField) -> Self {\n Self {\n token_type: item.token_type,\n }\n }\n}",
|
| 158 |
+
"diff_span": null,
|
| 159 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"id": "crates/router/src/types/transformers.rs::diesel_models::business_profile::VaultTokenField::function::foreign_from",
|
| 163 |
+
"file": "crates/router/src/types/transformers.rs",
|
| 164 |
+
"kind": "function_item",
|
| 165 |
+
"status": "added",
|
| 166 |
+
"before_code": null,
|
| 167 |
+
"after_code": "fn foreign_from(item: api_models::admin::VaultTokenField) -> Self {\n Self {\n token_type: item.token_type,\n }\n }",
|
| 168 |
+
"diff_span": null,
|
| 169 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"id": "crates/common_enums/src/enums.rs::enum::VaultTokenField",
|
| 173 |
+
"file": "crates/common_enums/src/enums.rs",
|
| 174 |
+
"kind": "enum_item",
|
| 175 |
+
"status": "removed",
|
| 176 |
+
"before_code": "pub enum VaultTokenField {\n /// Card number\n CardNumber,\n /// Card cvc\n CardCvc,\n /// Card expiry year\n CardExpiryYear,\n /// Card expiry month\n CardExpiryMonth,\n /// Network token\n NetworkToken,\n /// Token expiry year\n TokenExpiryYear,\n /// Token expiry month\n TokenExpiryMonth,\n /// Token cryptogram\n TokenCryptogram,\n}",
|
| 177 |
+
"after_code": null,
|
| 178 |
+
"diff_span": null,
|
| 179 |
+
"commit_sha": "e27aae926a3405171f6f73080b1fb79b84ed316b"
|
| 180 |
+
}
|
| 181 |
+
]
|
| 182 |
+
}
|
diffs/pr_10190/e2b7d7e/diff.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "e2b7d7e0b24af2121c9089e2d6b5651fd9f26981",
|
| 3 |
+
"pr_number": 10190,
|
| 4 |
+
"rust_files": [],
|
| 5 |
+
"diffs": []
|
| 6 |
+
}
|
diffs/pr_10193/abf1d0c/diff.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "abf1d0c35f33f1be8637d9370f5c6d547da9dbdb",
|
| 3 |
+
"pr_number": 10193,
|
| 4 |
+
"rust_files": [],
|
| 5 |
+
"diffs": []
|
| 6 |
+
}
|
diffs/pr_10206/0faf91f/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_10206/122ff42/diff.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "122ff42bf58be2e7ab6d5d2498e16c44c82e16e4",
|
| 3 |
+
"pr_number": 10206,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/workflows/revenue_recovery.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::should_force_schedule_due_to_missed_slots",
|
| 10 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n // Check monthly retry remaining first\n let has_monthly_retries = token_with_retry_info.monthly_retry_remaining >= 1;\n \n // If no monthly retries available, don't force schedule\n if !has_monthly_retries {\n return Ok(false);\n }\n\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 16 |
+
"after_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n // Check monthly retry remaining first\n let has_monthly_retries = token_with_retry_info.monthly_retry_remaining >= 1;\n\n // If no monthly retries available, don't force schedule\n if !has_monthly_retries {\n return Ok(false);\n }\n\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " // Check monthly retry remaining first\n let has_monthly_retries = token_with_retry_info.monthly_retry_remaining >= 1;\n \n // If no monthly retries available, don't force schedule\n if !has_monthly_retries {",
|
| 19 |
+
"after": " // Check monthly retry remaining first\n let has_monthly_retries = token_with_retry_info.monthly_retry_remaining >= 1;\n\n // If no monthly retries available, don't force schedule\n if !has_monthly_retries {"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "122ff42bf58be2e7ab6d5d2498e16c44c82e16e4"
|
| 22 |
+
}
|
| 23 |
+
]
|
| 24 |
+
}
|
diffs/pr_10206/33fad37/diff.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "33fad377a8ac6bbbd4b733aee9de5f5f297e0164",
|
| 3 |
+
"pr_number": 10206,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/workflows/revenue_recovery.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::should_force_schedule_due_to_missed_slots",
|
| 10 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 16 |
+
"after_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n // Check monthly retry remaining first\n let has_monthly_retries = token_with_retry_info.monthly_retry_remaining >= 1;\n \n // If no monthly retries available, don't force schedule\n if !has_monthly_retries {\n return Ok(false);\n }\n\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": "",
|
| 19 |
+
"after": " token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n // Check monthly retry remaining first\n let has_monthly_retries = token_with_retry_info.monthly_retry_remaining >= 1;\n \n // If no monthly retries available, don't force schedule\n if !has_monthly_retries {\n return Ok(false);\n }\n\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "33fad377a8ac6bbbd4b733aee9de5f5f297e0164"
|
| 22 |
+
}
|
| 23 |
+
]
|
| 24 |
+
}
|
diffs/pr_10206/49029b5/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_10206/4c2d145/diff.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "4c2d1456af3ab01555bc8b15d24a101c6f4336eb",
|
| 3 |
+
"pr_number": 10206,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/workflows/revenue_recovery.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::should_force_schedule_due_to_missed_slots",
|
| 10 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n connector_customer_id: &str,\n token: Secret<String, PhoneNumberStrategy>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH \n / state.conf.revenue_recovery.card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n \n // Calculate time difference and compare\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc())\n .whole_hours() > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 16 |
+
"after_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n connector_customer_id: &str,\n token: Secret<String, PhoneNumberStrategy>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference and compare\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH \n / state.conf.revenue_recovery.card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n \n // Calculate time difference and compare\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc())\n .whole_hours() > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)",
|
| 19 |
+
"after": ") -> CustomResult<bool, StorageError> {\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference and compare\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "4c2d1456af3ab01555bc8b15d24a101c6f4336eb"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::calculate_smart_retry_time",
|
| 25 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 26 |
+
"kind": "function_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "pub async fn calculate_smart_retry_time(\n state: &SessionState,\n payment_intent: &PaymentIntent,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // do a check, if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(\n state,\n card_network.clone(),\n connector_customer_id,\n masked_token.clone(),\n token_with_retry_info\n )\n .await\n .unwrap_or(false)\n {\n let schedule_delay = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::minutes(schedule_delay);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token.clone(),\n scheduled_time\n );\n return Ok(Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )));\n }\n\n get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await\n}",
|
| 31 |
+
"after_code": "pub async fn calculate_smart_retry_time(\n state: &SessionState,\n payment_intent: &PaymentIntent,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // do a check, if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(\n state,\n card_network.clone(),\n connector_customer_id,\n masked_token.clone(),\n token_with_retry_info,\n )\n .await\n .unwrap_or(false)\n {\n let schedule_delay = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::minutes(schedule_delay);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token.clone(),\n scheduled_time\n );\n return Ok(Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )));\n }\n\n get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await\n}",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " connector_customer_id,\n masked_token.clone(),\n token_with_retry_info\n )\n .await",
|
| 34 |
+
"after": " connector_customer_id,\n masked_token.clone(),\n token_with_retry_info,\n )\n .await"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "4c2d1456af3ab01555bc8b15d24a101c6f4336eb"
|
| 37 |
+
}
|
| 38 |
+
]
|
| 39 |
+
}
|
diffs/pr_10206/8cff7e3/diff.json
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "8cff7e325d4c08eb4eb7273cbb453b9349d9dfc2",
|
| 3 |
+
"pr_number": 10206,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/workflows/revenue_recovery.rs",
|
| 6 |
+
"crates/scheduler/src/utils.rs"
|
| 7 |
+
],
|
| 8 |
+
"diffs": [
|
| 9 |
+
{
|
| 10 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::should_force_schedule_due_to_missed_slots",
|
| 11 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 12 |
+
"kind": "function_item",
|
| 13 |
+
"status": "modified",
|
| 14 |
+
"code_changed": true,
|
| 15 |
+
"imports_changed": true,
|
| 16 |
+
"before_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n connector_customer_id: &str,\n token: Secret<String, PhoneNumberStrategy>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference and compare\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 17 |
+
"after_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n \n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc())\n .whole_hours() > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 18 |
+
"diff_span": {
|
| 19 |
+
"before": " state: &SessionState,\n card_network: Option<CardNetwork>,\n connector_customer_id: &str,\n token: Secret<String, PhoneNumberStrategy>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference and compare\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)",
|
| 20 |
+
"after": " .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n \n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc())\n .whole_hours() > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)"
|
| 21 |
+
},
|
| 22 |
+
"commit_sha": "8cff7e325d4c08eb4eb7273cbb453b9349d9dfc2",
|
| 23 |
+
"before_imports": [
|
| 24 |
+
"use time::Date;",
|
| 25 |
+
"use masking::{ExposeInterface, PeekInterface, Secret};",
|
| 26 |
+
"use crate::types::storage::{\n revenue_recovery::RetryLimitsConfig,\n revenue_recovery_redis_operation::{\n PaymentProcessorTokenStatus, PaymentProcessorTokenWithRetryInfo, RedisTokenManager,\n },\n};",
|
| 27 |
+
"use router_env::{\n logger,\n tracing::{self, instrument},\n};",
|
| 28 |
+
"use common_utils::errors::CustomResult;"
|
| 29 |
+
],
|
| 30 |
+
"after_imports": [
|
| 31 |
+
"use crate::types::storage::{\n revenue_recovery::RetryLimitsConfig,\n revenue_recovery_redis_operation::{\n PaymentProcessorTokenStatus, PaymentProcessorTokenWithRetryInfo, RedisTokenManager,\n },\n};",
|
| 32 |
+
"use router_env::{\n logger,\n tracing::{self, instrument},\n};",
|
| 33 |
+
"use common_utils::errors::CustomResult;",
|
| 34 |
+
"use time::Date;"
|
| 35 |
+
]
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"id": "crates/scheduler/src/utils.rs::function::divide_and_append_tasks",
|
| 39 |
+
"file": "crates/scheduler/src/utils.rs",
|
| 40 |
+
"kind": "function_item",
|
| 41 |
+
"status": "modified",
|
| 42 |
+
"code_changed": true,
|
| 43 |
+
"imports_changed": false,
|
| 44 |
+
"before_code": "pub async fn divide_and_append_tasks<T>(\n state: &T,\n flow: SchedulerFlow,\n tasks: Vec<storage::ProcessTracker>,\n settings: &SchedulerSettings,\n) -> CustomResult<(), errors::ProcessTrackerError>\nwhere\n T: SchedulerInterface + Send + Sync + ?Sized,\n{\n let batches = divide(tasks, settings);\n // Safety: Assuming we won't deal with more than `u64::MAX` batches at once\n #[allow(clippy::as_conversions)]\n metrics::BATCHES_CREATED.add(batches.len() as u64, &[]); // Metrics\n for batch in batches {\n let result = update_status_and_append(state, flow, batch).await;\n match result {\n Ok(_) => (),\n Err(error) => logger::error!(?error),\n }\n }\n Ok(())\n}",
|
| 45 |
+
"after_code": "pub async fn divide_and_append_tasks<T>(\n state: &T,\n flow: SchedulerFlow,\n tasks: Vec<storage::ProcessTracker>,\n settings: &SchedulerSettings,\n) -> CustomResult<(), errors::ProcessTrackerError>\nwhere\n T: SchedulerInterface + Send + Sync + ?Sized,\n{\n let batches = divide(tasks, settings);\n // Safety: Assuming we won't deal with more than `u64::MAX` batches at once\n logger::info!(\"Adding {} batches to stream\", batches.len());\n #[allow(clippy::as_conversions)]\n metrics::BATCHES_CREATED.add(batches.len() as u64, &[]); // Metrics\n for batch in batches {\n let result = update_status_and_append(state, flow, batch).await;\n match result {\n Ok(_) => (),\n Err(error) => logger::error!(?error),\n }\n }\n Ok(())\n}",
|
| 46 |
+
"diff_span": {
|
| 47 |
+
"before": "",
|
| 48 |
+
"after": " let batches = divide(tasks, settings);\n // Safety: Assuming we won't deal with more than `u64::MAX` batches at once\n logger::info!(\"Adding {} batches to stream\", batches.len());\n #[allow(clippy::as_conversions)]\n metrics::BATCHES_CREATED.add(batches.len() as u64, &[]); // Metrics"
|
| 49 |
+
},
|
| 50 |
+
"commit_sha": "8cff7e325d4c08eb4eb7273cbb453b9349d9dfc2"
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::calculate_smart_retry_time",
|
| 54 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 55 |
+
"kind": "function_item",
|
| 56 |
+
"status": "modified",
|
| 57 |
+
"code_changed": true,
|
| 58 |
+
"imports_changed": false,
|
| 59 |
+
"before_code": "pub async fn calculate_smart_retry_time(\n state: &SessionState,\n payment_intent: &PaymentIntent,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // do a check, if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(\n state,\n card_network.clone(),\n connector_customer_id,\n masked_token.clone(),\n token_with_retry_info,\n )\n .await\n .unwrap_or(false)\n {\n let schedule_delay = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::minutes(schedule_delay);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token.clone(),\n scheduled_time\n );\n return Ok(Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )));\n }\n\n get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await\n}",
|
| 60 |
+
"after_code": "pub async fn calculate_smart_retry_time(\n state: &SessionState,\n payment_intent: &PaymentIntent,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<(Option<time::PrimitiveDateTime>, bool), errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token: Secret<_, PhoneNumberStrategy> = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // Check if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(\n state,\n card_network.clone(),\n token_with_retry_info\n )\n .await\n .unwrap_or(false)\n {\n let schedule_offset = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token,\n scheduled_time\n );\n return Ok((Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )), true)); // force_scheduled = true\n }\n\n // Normal smart retry path\n let schedule_time = get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await?;\n \n Ok((schedule_time, false)) // force_scheduled = false\n}",
|
| 61 |
+
"diff_span": {
|
| 62 |
+
"before": " token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // do a check, if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(\n state,\n card_network.clone(),\n connector_customer_id,\n masked_token.clone(),\n token_with_retry_info,\n )\n .await\n .unwrap_or(false)\n {\n let schedule_delay = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::minutes(schedule_delay);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token.clone(),\n scheduled_time\n );\n return Ok(Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )));\n }\n\n get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await\n}",
|
| 63 |
+
"after": " token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<(Option<time::PrimitiveDateTime>, bool), errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token: Secret<_, PhoneNumberStrategy> = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // Check if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(\n state,\n card_network.clone(),\n token_with_retry_info\n )\n .await\n .unwrap_or(false)\n {\n let schedule_offset = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token,\n scheduled_time\n );\n return Ok((Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )), true)); // force_scheduled = true\n }\n\n // Normal smart retry path\n let schedule_time = get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await?;\n \n Ok((schedule_time, false)) // force_scheduled = false\n}"
|
| 64 |
+
},
|
| 65 |
+
"commit_sha": "8cff7e325d4c08eb4eb7273cbb453b9349d9dfc2"
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::call_decider_for_payment_processor_tokens_select_closest_time",
|
| 69 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 70 |
+
"kind": "function_item",
|
| 71 |
+
"status": "modified",
|
| 72 |
+
"code_changed": true,
|
| 73 |
+
"imports_changed": false,
|
| 74 |
+
"before_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n for token_with_retry_info in processor_tokens.values() {\n process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?\n .map(|token_with_schedule_time| {\n tokens_with_schedule_time.push(token_with_schedule_time)\n });\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 75 |
+
"after_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n \n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?;\n \n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n \n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {\n force_scheduled_found = true;\n tracing::info!(\n \"Force-scheduled token detected due to missed slots, breaking early from token processing\"\n );\n break; // Stop processing remaining tokens immediately\n }\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 76 |
+
"diff_span": {
|
| 77 |
+
"before": " None => {\n for token_with_retry_info in processor_tokens.values() {\n process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?\n .map(|token_with_schedule_time| {\n tokens_with_schedule_time.push(token_with_schedule_time)\n });\n }\n }",
|
| 78 |
+
"after": "\n None => {\n // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n \n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?;\n \n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n \n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {\n force_scheduled_found = true;\n tracing::info!(\n \"Force-scheduled token detected due to missed slots, breaking early from token processing\"\n );\n break; // Stop processing remaining tokens immediately\n }\n }\n }"
|
| 79 |
+
},
|
| 80 |
+
"commit_sha": "8cff7e325d4c08eb4eb7273cbb453b9349d9dfc2"
|
| 81 |
+
},
|
| 82 |
+
{
|
| 83 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::process_token_for_retry",
|
| 84 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 85 |
+
"kind": "function_item",
|
| 86 |
+
"status": "modified",
|
| 87 |
+
"code_changed": true,
|
| 88 |
+
"imports_changed": false,
|
| 89 |
+
"before_code": "async fn process_token_for_retry(\n state: &SessionState,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> Result<Option<ScheduledToken>, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(None)\n }\n false => {\n let schedule_time = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n connector_customer_id,\n )\n .await?;\n Ok(schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }))\n }\n }\n}",
|
| 90 |
+
"after_code": "async fn process_token_for_retry(\n state: &SessionState,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> Result<TokenProcessResult, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(TokenProcessResult {\n scheduled_token: None,\n force_scheduled: false,\n })\n }\n false => {\n let (schedule_time, force_scheduled) = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n connector_customer_id,\n )\n .await?;\n \n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }),\n force_scheduled,\n })\n }\n }\n}",
|
| 91 |
+
"diff_span": {
|
| 92 |
+
"before": " payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> Result<Option<ScheduledToken>, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(None)\n }\n false => {\n let schedule_time = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n connector_customer_id,\n )\n .await?;\n Ok(schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }))\n }\n }",
|
| 93 |
+
"after": " payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> Result<TokenProcessResult, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(TokenProcessResult {\n scheduled_token: None,\n force_scheduled: false,\n })\n }\n false => {\n let (schedule_time, force_scheduled) = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n connector_customer_id,\n )\n .await?;\n \n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }),\n force_scheduled,\n })\n }\n }"
|
| 94 |
+
},
|
| 95 |
+
"commit_sha": "8cff7e325d4c08eb4eb7273cbb453b9349d9dfc2"
|
| 96 |
+
},
|
| 97 |
+
{
|
| 98 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::struct::TokenProcessResult",
|
| 99 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 100 |
+
"kind": "struct_item",
|
| 101 |
+
"status": "added",
|
| 102 |
+
"before_code": null,
|
| 103 |
+
"after_code": "struct TokenProcessResult {\n scheduled_token: Option<ScheduledToken>,\n force_scheduled: bool,\n}",
|
| 104 |
+
"diff_span": null,
|
| 105 |
+
"commit_sha": "8cff7e325d4c08eb4eb7273cbb453b9349d9dfc2"
|
| 106 |
+
}
|
| 107 |
+
]
|
| 108 |
+
}
|
diffs/pr_10206/9354823/diff.json
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "9354823eb6d0cf1af58924aeeeaf46190028cf76",
|
| 3 |
+
"pr_number": 10206,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/workflows/revenue_recovery.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::calculate_smart_retry_time",
|
| 10 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "pub async fn calculate_smart_retry_time(\n state: &SessionState,\n payment_intent: &PaymentIntent,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<(Option<time::PrimitiveDateTime>, bool), errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token: Secret<_, PhoneNumberStrategy> = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // Check if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(state, card_network.clone(), token_with_retry_info)\n .await\n .unwrap_or(false)\n {\n let schedule_offset = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token,\n scheduled_time\n );\n return Ok((\n Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )),\n true,\n )); // force_scheduled = true\n }\n\n // Normal smart retry path\n let schedule_time = get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await?;\n\n Ok((schedule_time, false)) // force_scheduled = false\n}",
|
| 16 |
+
"after_code": "pub async fn calculate_smart_retry_time(\n state: &SessionState,\n payment_intent: &PaymentIntent,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> Result<(Option<time::PrimitiveDateTime>, bool), errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token: Secret<_, PhoneNumberStrategy> = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // Check if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(state, card_network.clone(), token_with_retry_info)\n .await\n .unwrap_or(false)\n {\n let schedule_offset = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for the token:- '{:?}' to time:- {}\",\n masked_token,\n scheduled_time\n );\n return Ok((\n Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )),\n true,\n )); // force_scheduled = true\n }\n\n // Normal smart retry path\n let schedule_time = get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await?;\n\n Ok((schedule_time, false)) // force_scheduled = false\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " payment_intent: &PaymentIntent,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<(Option<time::PrimitiveDateTime>, bool), errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token: Secret<_, PhoneNumberStrategy> = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // Check if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(state, card_network.clone(), token_with_retry_info)\n .await\n .unwrap_or(false)\n {\n let schedule_offset = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token,\n scheduled_time",
|
| 19 |
+
"after": " time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for the token:- '{:?}' to time:- {}\",\n masked_token,\n scheduled_time"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "9354823eb6d0cf1af58924aeeeaf46190028cf76"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::call_decider_for_payment_processor_tokens_select_closest_time",
|
| 25 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 26 |
+
"kind": "function_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n\n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?;\n\n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n\n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {\n force_scheduled_found = true;\n tracing::info!(\n \"Force-scheduled token detected due to missed slots, breaking early from token processing\"\n );\n break; // Stop processing remaining tokens immediately\n }\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 31 |
+
"after_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n\n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n )\n .await?;\n\n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n\n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {\n force_scheduled_found = true;\n tracing::info!(\n \"Force-scheduled token detected due to missed slots, breaking early from token processing\"\n );\n break; // Stop processing remaining tokens immediately\n }\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?;",
|
| 34 |
+
"after": ""
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "9354823eb6d0cf1af58924aeeeaf46190028cf76"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::process_token_for_retry",
|
| 40 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 41 |
+
"kind": "function_item",
|
| 42 |
+
"status": "modified",
|
| 43 |
+
"code_changed": true,
|
| 44 |
+
"imports_changed": false,
|
| 45 |
+
"before_code": "async fn process_token_for_retry(\n state: &SessionState,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> Result<TokenProcessResult, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(TokenProcessResult {\n scheduled_token: None,\n force_scheduled: false,\n })\n }\n false => {\n let (schedule_time, force_scheduled) = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n connector_customer_id,\n )\n .await?;\n\n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }),\n force_scheduled,\n })\n }\n }\n}",
|
| 46 |
+
"after_code": "async fn process_token_for_retry(\n state: &SessionState,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n payment_intent: &PaymentIntent,\n) -> Result<TokenProcessResult, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(TokenProcessResult {\n scheduled_token: None,\n force_scheduled: false,\n })\n }\n false => {\n let (schedule_time, force_scheduled) = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n )\n .await?;\n\n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }),\n force_scheduled,\n })\n }\n }\n}",
|
| 47 |
+
"diff_span": {
|
| 48 |
+
"before": " token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> Result<TokenProcessResult, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(TokenProcessResult {\n scheduled_token: None,\n force_scheduled: false,\n })\n }\n false => {\n let (schedule_time, force_scheduled) = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n connector_customer_id,\n )\n .await?;",
|
| 49 |
+
"after": ""
|
| 50 |
+
},
|
| 51 |
+
"commit_sha": "9354823eb6d0cf1af58924aeeeaf46190028cf76"
|
| 52 |
+
}
|
| 53 |
+
]
|
| 54 |
+
}
|
diffs/pr_10206/ae9a3da/diff.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "ae9a3da9b9e376a9ed3c2f14b0a4451b339c2be2",
|
| 3 |
+
"pr_number": 10206,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/workflows/revenue_recovery.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::call_decider_for_payment_processor_tokens_select_closest_time",
|
| 10 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n\n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n )\n .await?;\n\n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n\n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {\n force_scheduled_found = true;\n tracing::info!(\n \"Force-scheduled token detected due to missed slots, breaking early from token processing\"\n );\n break; // Stop processing remaining tokens immediately\n }\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 16 |
+
"after_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n\n for token_with_retry_info in processor_tokens.values() {\n let result =\n process_token_for_retry(state, token_with_retry_info, payment_intent).await?;\n\n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n\n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {\n force_scheduled_found = true;\n tracing::info!(\n \"Force-scheduled token detected due to missed slots, breaking early from token processing\"\n );\n break; // Stop processing remaining tokens immediately\n }\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": "\n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n )\n .await?;\n\n // Add the scheduled token if it exists",
|
| 19 |
+
"after": "\n for token_with_retry_info in processor_tokens.values() {\n let result =\n process_token_for_retry(state, token_with_retry_info, payment_intent).await?;\n\n // Add the scheduled token if it exists"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "ae9a3da9b9e376a9ed3c2f14b0a4451b339c2be2"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::process_token_for_retry",
|
| 25 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 26 |
+
"kind": "function_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "async fn process_token_for_retry(\n state: &SessionState,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n payment_intent: &PaymentIntent,\n) -> Result<TokenProcessResult, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(TokenProcessResult {\n scheduled_token: None,\n force_scheduled: false,\n })\n }\n false => {\n let (schedule_time, force_scheduled) = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n )\n .await?;\n\n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }),\n force_scheduled,\n })\n }\n }\n}",
|
| 31 |
+
"after_code": "async fn process_token_for_retry(\n state: &SessionState,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n payment_intent: &PaymentIntent,\n) -> Result<TokenProcessResult, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(TokenProcessResult {\n scheduled_token: None,\n force_scheduled: false,\n })\n }\n false => {\n let (schedule_time, force_scheduled) =\n calculate_smart_retry_time(state, payment_intent, token_with_retry_info).await?;\n\n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }),\n force_scheduled,\n })\n }\n }\n}",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " }\n false => {\n let (schedule_time, force_scheduled) = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n )\n .await?;\n\n Ok(TokenProcessResult {",
|
| 34 |
+
"after": " }\n false => {\n let (schedule_time, force_scheduled) =\n calculate_smart_retry_time(state, payment_intent, token_with_retry_info).await?;\n\n Ok(TokenProcessResult {"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "ae9a3da9b9e376a9ed3c2f14b0a4451b339c2be2"
|
| 37 |
+
}
|
| 38 |
+
]
|
| 39 |
+
}
|
diffs/pr_10206/b822b6c/diff.json
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "b822b6c720e8b5df4a71b67e3eb5c46e34cb6210",
|
| 3 |
+
"pr_number": 10206,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/workflows/revenue_recovery.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::should_force_schedule_due_to_missed_slots",
|
| 10 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n \n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc())\n .whole_hours() > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 16 |
+
"after_code": "async fn should_force_schedule_due_to_missed_slots(\n state: &SessionState,\n card_network: Option<CardNetwork>,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n) -> CustomResult<bool, StorageError> {\n Ok(RedisTokenManager::find_nearest_date_from_current(\n &token_with_retry_info.token_status.daily_retry_history,\n )\n // Filter: only consider entries with actual retries (retry_count > 0)\n .filter(|(_, retry_count)| *retry_count > 0)\n .map(|(most_recent_date, _retry_count)| {\n let threshold_hours = TOTAL_SLOTS_IN_MONTH\n / state\n .conf\n .revenue_recovery\n .card_config\n .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)\n .unwrap_or(false))\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n \n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc())\n .whole_hours() > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)",
|
| 19 |
+
"after": " .get_network_config(card_network.clone())\n .max_retry_count_for_thirty_day;\n\n // Calculate time difference since last retry and compare with threshold\n (time::OffsetDateTime::now_utc() - most_recent_date.midnight().assume_utc()).whole_hours()\n > threshold_hours.into()\n })\n // Default to false if no valid retry history found (either none exists or all have retry_count = 0)"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "b822b6c720e8b5df4a71b67e3eb5c46e34cb6210"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::calculate_smart_retry_time",
|
| 25 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 26 |
+
"kind": "function_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "pub async fn calculate_smart_retry_time(\n state: &SessionState,\n payment_intent: &PaymentIntent,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<(Option<time::PrimitiveDateTime>, bool), errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token: Secret<_, PhoneNumberStrategy> = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // Check if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(\n state,\n card_network.clone(),\n token_with_retry_info\n )\n .await\n .unwrap_or(false)\n {\n let schedule_offset = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token,\n scheduled_time\n );\n return Ok((Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )), true)); // force_scheduled = true\n }\n\n // Normal smart retry path\n let schedule_time = get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await?;\n \n Ok((schedule_time, false)) // force_scheduled = false\n}",
|
| 31 |
+
"after_code": "pub async fn calculate_smart_retry_time(\n state: &SessionState,\n payment_intent: &PaymentIntent,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n connector_customer_id: &str,\n) -> Result<(Option<time::PrimitiveDateTime>, bool), errors::ProcessTrackerError> {\n let wait_hours = token_with_retry_info.retry_wait_time_hours;\n let current_time = time::OffsetDateTime::now_utc();\n let future_time = current_time + time::Duration::hours(wait_hours);\n\n // Timestamp after which retry can be done without penalty\n let future_timestamp = Some(prost_types::Timestamp {\n seconds: future_time.unix_timestamp(),\n nanos: 0,\n });\n\n let token = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .payment_processor_token\n .clone();\n\n let masked_token: Secret<_, PhoneNumberStrategy> = Secret::new(token);\n\n let card_info = token_with_retry_info\n .token_status\n .payment_processor_token_details\n .clone();\n\n let card_network = card_info.card_network.clone();\n\n // Check if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(state, card_network.clone(), token_with_retry_info)\n .await\n .unwrap_or(false)\n {\n let schedule_offset = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token,\n scheduled_time\n );\n return Ok((\n Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )),\n true,\n )); // force_scheduled = true\n }\n\n // Normal smart retry path\n let schedule_time = get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await?;\n\n Ok((schedule_time, false)) // force_scheduled = false\n}",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": "\n // Check if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(\n state,\n card_network.clone(),\n token_with_retry_info\n )\n .await\n .unwrap_or(false)\n {\n let schedule_offset = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token,\n scheduled_time\n );\n return Ok((Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )), true)); // force_scheduled = true\n }\n\n // Normal smart retry path\n let schedule_time = get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await?;\n \n Ok((schedule_time, false)) // force_scheduled = false\n}",
|
| 34 |
+
"after": "\n // Check if the last retry is not done within defined slot, force the retry to next slot\n if should_force_schedule_due_to_missed_slots(state, card_network.clone(), token_with_retry_info)\n .await\n .unwrap_or(false)\n {\n let schedule_offset = state\n .conf\n .revenue_recovery\n .recovery_timestamp\n .unretried_invoice_schedule_time_offset_seconds;\n let scheduled_time =\n time::OffsetDateTime::now_utc() + time::Duration::seconds(schedule_offset);\n logger::info!(\n \"Skipping Decider call, forcing a schedule for customer:- {} with the token:- '{:?}' to time:- {}\",\n connector_customer_id,\n masked_token,\n scheduled_time\n );\n return Ok((\n Some(time::PrimitiveDateTime::new(\n scheduled_time.date(),\n scheduled_time.time(),\n )),\n true,\n )); // force_scheduled = true\n }\n\n // Normal smart retry path\n let schedule_time = get_schedule_time_for_smart_retry(\n state,\n payment_intent,\n future_timestamp,\n token_with_retry_info,\n )\n .await?;\n\n Ok((schedule_time, false)) // force_scheduled = false\n}"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "b822b6c720e8b5df4a71b67e3eb5c46e34cb6210"
|
| 37 |
+
},
|
| 38 |
+
{
|
| 39 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::call_decider_for_payment_processor_tokens_select_closest_time",
|
| 40 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 41 |
+
"kind": "function_item",
|
| 42 |
+
"status": "modified",
|
| 43 |
+
"code_changed": true,
|
| 44 |
+
"imports_changed": false,
|
| 45 |
+
"before_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n \n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?;\n \n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n \n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {\n force_scheduled_found = true;\n tracing::info!(\n \"Force-scheduled token detected due to missed slots, breaking early from token processing\"\n );\n break; // Stop processing remaining tokens immediately\n }\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 46 |
+
"after_code": "pub async fn call_decider_for_payment_processor_tokens_select_closest_time(\n state: &SessionState,\n processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> CustomResult<PaymentProcessorTokenResponse, errors::ProcessTrackerError> {\n let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();\n\n // Check for successful token\n let mut token_with_none_error_code = processor_tokens.values().find(|token| {\n token.token_status.error_code.is_none()\n && !token.token_status.is_hard_decline.unwrap_or(false)\n });\n\n match token_with_none_error_code {\n Some(token_with_retry_info) => {\n let token_details = &token_with_retry_info\n .token_status\n .payment_processor_token_details;\n\n let utc_schedule_time = time::OffsetDateTime::now_utc() + time::Duration::minutes(1);\n let schedule_time =\n time::PrimitiveDateTime::new(utc_schedule_time.date(), utc_schedule_time.time());\n\n tokens_with_schedule_time = vec![ScheduledToken {\n token_details: token_details.clone(),\n schedule_time,\n }];\n\n tracing::debug!(\n \"Found payment processor token with no error code, scheduling it for {schedule_time}\",\n );\n }\n\n None => {\n // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n\n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?;\n\n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n\n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {\n force_scheduled_found = true;\n tracing::info!(\n \"Force-scheduled token detected due to missed slots, breaking early from token processing\"\n );\n break; // Stop processing remaining tokens immediately\n }\n }\n }\n }\n\n let best_token = tokens_with_schedule_time\n .iter()\n .min_by_key(|token| token.schedule_time)\n .cloned();\n\n let mut payment_processor_token_response;\n match best_token {\n None => {\n // No tokens available for scheduling, unlock the connector customer status\n\n // Check if all tokens are hard declined\n let hard_decline_status = processor_tokens\n .values()\n .all(|token| token.token_status.is_hard_decline.unwrap_or(false))\n && !processor_tokens.is_empty();\n\n RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n tracing::debug!(\"No payment processor tokens available for scheduling\");\n\n if hard_decline_status {\n payment_processor_token_response = PaymentProcessorTokenResponse::HardDecline;\n } else {\n payment_processor_token_response = PaymentProcessorTokenResponse::None;\n }\n }\n\n Some(token) => {\n tracing::debug!(\"Found payment processor token with least schedule time\");\n\n RedisTokenManager::update_payment_processor_tokens_schedule_time_to_none(\n state,\n connector_customer_id,\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n RedisTokenManager::update_payment_processor_token_schedule_time(\n state,\n connector_customer_id,\n &token.token_details.payment_processor_token,\n Some(token.schedule_time),\n )\n .await\n .change_context(errors::ProcessTrackerError::EApiErrorResponse)?;\n\n payment_processor_token_response = PaymentProcessorTokenResponse::ScheduledTime {\n scheduled_time: token.schedule_time,\n };\n }\n }\n Ok(payment_processor_token_response)\n}",
|
| 47 |
+
"diff_span": {
|
| 48 |
+
"before": " // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n \n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?;\n \n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n \n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {",
|
| 49 |
+
"after": " // Flag to track if we found a force-scheduled token\n let mut force_scheduled_found = false;\n\n for token_with_retry_info in processor_tokens.values() {\n let result = process_token_for_retry(\n state,\n token_with_retry_info,\n payment_intent,\n connector_customer_id,\n )\n .await?;\n\n // Add the scheduled token if it exists\n if let Some(scheduled_token) = result.scheduled_token {\n tokens_with_schedule_time.push(scheduled_token);\n }\n\n // Check if this was force-scheduled due to missed slots\n if result.force_scheduled {"
|
| 50 |
+
},
|
| 51 |
+
"commit_sha": "b822b6c720e8b5df4a71b67e3eb5c46e34cb6210"
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"id": "crates/router/src/workflows/revenue_recovery.rs::function::process_token_for_retry",
|
| 55 |
+
"file": "crates/router/src/workflows/revenue_recovery.rs",
|
| 56 |
+
"kind": "function_item",
|
| 57 |
+
"status": "modified",
|
| 58 |
+
"code_changed": true,
|
| 59 |
+
"imports_changed": false,
|
| 60 |
+
"before_code": "async fn process_token_for_retry(\n state: &SessionState,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> Result<TokenProcessResult, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(TokenProcessResult {\n scheduled_token: None,\n force_scheduled: false,\n })\n }\n false => {\n let (schedule_time, force_scheduled) = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n connector_customer_id,\n )\n .await?;\n \n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }),\n force_scheduled,\n })\n }\n }\n}",
|
| 61 |
+
"after_code": "async fn process_token_for_retry(\n state: &SessionState,\n token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,\n payment_intent: &PaymentIntent,\n connector_customer_id: &str,\n) -> Result<TokenProcessResult, errors::ProcessTrackerError> {\n let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;\n let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;\n\n let skip = token_status.is_hard_decline.unwrap_or(false);\n\n match skip {\n true => {\n logger::info!(\n \"Skipping decider call due to hard decline token inserted by attempt_id: {}\",\n inserted_by_attempt_id.get_string_repr()\n );\n Ok(TokenProcessResult {\n scheduled_token: None,\n force_scheduled: false,\n })\n }\n false => {\n let (schedule_time, force_scheduled) = calculate_smart_retry_time(\n state,\n payment_intent,\n token_with_retry_info,\n connector_customer_id,\n )\n .await?;\n\n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {\n token_details: token_status.payment_processor_token_details.clone(),\n schedule_time,\n }),\n force_scheduled,\n })\n }\n }\n}",
|
| 62 |
+
"diff_span": {
|
| 63 |
+
"before": " )\n .await?;\n \n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {",
|
| 64 |
+
"after": " )\n .await?;\n\n Ok(TokenProcessResult {\n scheduled_token: schedule_time.map(|schedule_time| ScheduledToken {"
|
| 65 |
+
},
|
| 66 |
+
"commit_sha": "b822b6c720e8b5df4a71b67e3eb5c46e34cb6210"
|
| 67 |
+
}
|
| 68 |
+
]
|
| 69 |
+
}
|
diffs/pr_6712/2443034/diff.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "244303420401898cdfdb2ce0ac872889c55452b2",
|
| 3 |
+
"pr_number": 6712,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/routes/app.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/routes/app.rs::User::function::server",
|
| 10 |
+
"file": "crates/router/src/routes/app.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "pub fn server(state: AppState) -> Scope {\n let mut route = web::scope(\"/user\").app_data(web::Data::new(state));\n\n route = route\n .service(web::resource(\"\").route(web::get().to(user::get_user_details)))\n .service(web::resource(\"/signin\").route(web::post().to(user::user_signin)))\n .service(web::resource(\"/v2/signin\").route(web::post().to(user::user_signin)))\n // signin/signup with sso using openidconnect\n .service(web::resource(\"/oidc\").route(web::post().to(user::sso_sign)))\n .service(web::resource(\"/signout\").route(web::post().to(user::signout)))\n .service(web::resource(\"/rotate_password\").route(web::post().to(user::rotate_password)))\n .service(web::resource(\"/change_password\").route(web::post().to(user::change_password)))\n .service(\n web::resource(\"/internal_signup\").route(web::post().to(user::internal_user_signup)),\n )\n .service(\n web::resource(\"/create_merchant\")\n .route(web::post().to(user::user_merchant_account_create)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/permission_info\")\n .route(web::get().to(user_role::get_authorization_info)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/module/list\").route(web::get().to(user_role::get_role_information)),\n )\n .service(\n web::resource(\"/parent/list\")\n .route(web::get().to(user_role::get_parent_group_info)),\n )\n .service(\n web::resource(\"/update\").route(web::post().to(user::update_user_account_details)),\n )\n .service(\n web::resource(\"/data\")\n .route(web::get().to(user::get_multiple_dashboard_metadata))\n .route(web::post().to(user::set_dashboard_metadata)),\n );\n\n route = route\n .service(web::scope(\"/key\").service(\n web::resource(\"/transfer\").route(web::post().to(user::transfer_user_key)),\n ));\n\n route = route.service(\n web::scope(\"/list\")\n .service(web::resource(\"/org\").route(web::get().to(user::list_orgs_for_user)))\n .service(\n web::resource(\"/merchant\")\n .route(web::get().to(user::list_merchants_for_user_in_org)),\n )\n .service(\n web::resource(\"/profile\")\n .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),\n )\n .service(\n web::resource(\"/invitation\")\n .route(web::get().to(user_role::list_invitations_for_user)),\n ),\n );\n\n route = route.service(\n web::scope(\"/switch\")\n .service(web::resource(\"/org\").route(web::post().to(user::switch_org_for_user)))\n .service(\n web::resource(\"/merchant\")\n .route(web::post().to(user::switch_merchant_for_user_in_org)),\n )\n .service(\n web::resource(\"/profile\")\n .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),\n ),\n );\n\n // Two factor auth routes\n route = route.service(\n web::scope(\"/2fa\")\n // TODO: to be deprecated\n .service(web::resource(\"\").route(web::get().to(user::check_two_factor_auth_status)))\n .service(\n web::resource(\"/v2\")\n .route(web::get().to(user::check_two_factor_auth_status_with_attempts)),\n )\n .service(\n web::scope(\"/totp\")\n .service(web::resource(\"/begin\").route(web::get().to(user::totp_begin)))\n .service(web::resource(\"/reset\").route(web::get().to(user::totp_reset)))\n .service(\n web::resource(\"/verify\")\n .route(web::post().to(user::totp_verify))\n .route(web::put().to(user::totp_update)),\n ),\n )\n .service(\n web::scope(\"/recovery_code\")\n .service(\n web::resource(\"/verify\")\n .route(web::post().to(user::verify_recovery_code)),\n )\n .service(\n web::resource(\"/generate\")\n .route(web::get().to(user::generate_recovery_codes)),\n ),\n )\n .service(\n web::resource(\"/terminate\")\n .route(web::get().to(user::terminate_two_factor_auth)),\n ),\n );\n\n route = route.service(\n web::scope(\"/auth\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user::create_user_authentication_method))\n .route(web::put().to(user::update_user_authentication_method)),\n )\n .service(\n web::resource(\"/list\")\n .route(web::get().to(user::list_user_authentication_methods)),\n )\n .service(web::resource(\"/url\").route(web::get().to(user::get_sso_auth_url)))\n .service(\n web::resource(\"/select\").route(web::post().to(user::terminate_auth_select)),\n ),\n );\n\n #[cfg(feature = \"email\")]\n {\n route = route\n .service(web::resource(\"/from_email\").route(web::post().to(user::user_from_email)))\n .service(\n web::resource(\"/connect_account\")\n .route(web::post().to(user::user_connect_account)),\n )\n .service(\n web::resource(\"/forgot_password\").route(web::post().to(user::forgot_password)),\n )\n .service(\n web::resource(\"/reset_password\").route(web::post().to(user::reset_password)),\n )\n .service(\n web::resource(\"/signup_with_merchant_id\")\n .route(web::post().to(user::user_signup_with_merchant_id)),\n )\n .service(web::resource(\"/verify_email\").route(web::post().to(user::verify_email)))\n .service(\n web::resource(\"/v2/verify-email\").route(web::post().to(user::verify_email)),\n )\n .service(\n web::resource(\"/verify_email_request\")\n .route(web::post().to(user::verify_email_request)),\n )\n .service(\n web::resource(\"/user/resend_invite\").route(web::post().to(user::resend_invite)),\n )\n .service(\n web::resource(\"/accept_invite_from_email\")\n .route(web::post().to(user::accept_invite_from_email)),\n );\n }\n #[cfg(not(feature = \"email\"))]\n {\n route = route.service(web::resource(\"/signup\").route(web::post().to(user::user_signup)))\n }\n\n // User management\n route = route.service(\n web::scope(\"/user\")\n .service(web::resource(\"\").route(web::post().to(user::list_user_roles_details)))\n // TODO: To be deprecated\n .service(web::resource(\"/v2\").route(web::post().to(user::list_user_roles_details)))\n .service(\n web::resource(\"/list\").route(web::get().to(user_role::list_users_in_lineage)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_users_in_lineage)),\n )\n .service(\n web::resource(\"/invite_multiple\")\n .route(web::post().to(user::invite_multiple_user)),\n )\n .service(\n web::scope(\"/invite/accept\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\")\n .route(web::post().to(user_role::accept_invitations_pre_auth)),\n )\n .service(\n web::scope(\"/v2\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre-auth\").route(\n web::post().to(user_role::accept_invitations_pre_auth),\n ),\n ),\n ),\n )\n .service(\n web::resource(\"/update_role\")\n .route(web::post().to(user_role::update_user_role)),\n )\n .service(\n web::resource(\"/delete\").route(web::delete().to(user_role::delete_user_role)),\n ),\n );\n\n // Role information\n route =\n route.service(\n web::scope(\"/role\")\n .service(\n web::resource(\"\")\n .route(web::get().to(user_role::get_role_from_token))\n .route(web::post().to(user_role::create_role)),\n )\n .service(web::resource(\"/v2\").route(\n web::get().to(user_role::get_groups_and_resources_for_role_from_token),\n ))\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_roles_with_info)),\n )\n .service(\n web::scope(\"/list\")\n .service(\n web::resource(\"\")\n .route(web::get().to(user_role::list_roles_with_info)),\n )\n .service(web::resource(\"/invite\").route(\n web::get().to(user_role::list_invitable_roles_at_entity_level),\n ))\n .service(web::resource(\"/update\").route(\n web::get().to(user_role::list_updatable_roles_at_entity_level),\n )),\n )\n .service(\n web::resource(\"/{role_id}\")\n .route(web::get().to(user_role::get_role))\n .route(web::put().to(user_role::update_role)),\n )\n .service(\n web::resource(\"/{role_id}/v2\")\n .route(web::get().to(user_role::get_parent_info_for_role)),\n ),\n );\n\n #[cfg(feature = \"dummy_connector\")]\n {\n route = route.service(\n web::resource(\"/sample_data\")\n .route(web::post().to(user::generate_sample_data))\n .route(web::delete().to(user::delete_sample_data)),\n )\n }\n route\n }",
|
| 16 |
+
"after_code": "pub fn server(state: AppState) -> Scope {\n let mut route = web::scope(\"/user\").app_data(web::Data::new(state));\n\n route = route\n .service(web::resource(\"\").route(web::get().to(user::get_user_details)))\n .service(web::resource(\"/signin\").route(web::post().to(user::user_signin)))\n .service(web::resource(\"/v2/signin\").route(web::post().to(user::user_signin)))\n // signin/signup with sso using openidconnect\n .service(web::resource(\"/oidc\").route(web::post().to(user::sso_sign)))\n .service(web::resource(\"/signout\").route(web::post().to(user::signout)))\n .service(web::resource(\"/rotate_password\").route(web::post().to(user::rotate_password)))\n .service(web::resource(\"/change_password\").route(web::post().to(user::change_password)))\n .service(\n web::resource(\"/internal_signup\").route(web::post().to(user::internal_user_signup)),\n )\n .service(\n web::resource(\"/create_merchant\")\n .route(web::post().to(user::user_merchant_account_create)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/permission_info\")\n .route(web::get().to(user_role::get_authorization_info)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/module/list\").route(web::get().to(user_role::get_role_information)),\n )\n .service(\n web::resource(\"/parent/list\")\n .route(web::get().to(user_role::get_parent_group_info)),\n )\n .service(\n web::resource(\"/update\").route(web::post().to(user::update_user_account_details)),\n )\n .service(\n web::resource(\"/data\")\n .route(web::get().to(user::get_multiple_dashboard_metadata))\n .route(web::post().to(user::set_dashboard_metadata)),\n );\n\n route = route\n .service(web::scope(\"/key\").service(\n web::resource(\"/transfer\").route(web::post().to(user::transfer_user_key)),\n ));\n\n route = route.service(\n web::scope(\"/list\")\n .service(web::resource(\"/org\").route(web::get().to(user::list_orgs_for_user)))\n .service(\n web::resource(\"/merchant\")\n .route(web::get().to(user::list_merchants_for_user_in_org)),\n )\n .service(\n web::resource(\"/profile\")\n .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),\n )\n .service(\n web::resource(\"/invitation\")\n .route(web::get().to(user_role::list_invitations_for_user)),\n ),\n );\n\n route = route.service(\n web::scope(\"/switch\")\n .service(web::resource(\"/org\").route(web::post().to(user::switch_org_for_user)))\n .service(\n web::resource(\"/merchant\")\n .route(web::post().to(user::switch_merchant_for_user_in_org)),\n )\n .service(\n web::resource(\"/profile\")\n .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),\n ),\n );\n\n // Two factor auth routes\n route = route.service(\n web::scope(\"/2fa\")\n // TODO: to be deprecated\n .service(web::resource(\"\").route(web::get().to(user::check_two_factor_auth_status)))\n .service(\n web::resource(\"/v2\")\n .route(web::get().to(user::check_two_factor_auth_status_with_attempts)),\n )\n .service(\n web::scope(\"/totp\")\n .service(web::resource(\"/begin\").route(web::get().to(user::totp_begin)))\n .service(web::resource(\"/reset\").route(web::get().to(user::totp_reset)))\n .service(\n web::resource(\"/verify\")\n .route(web::post().to(user::totp_verify))\n .route(web::put().to(user::totp_update)),\n ),\n )\n .service(\n web::scope(\"/recovery_code\")\n .service(\n web::resource(\"/verify\")\n .route(web::post().to(user::verify_recovery_code)),\n )\n .service(\n web::resource(\"/generate\")\n .route(web::get().to(user::generate_recovery_codes)),\n ),\n )\n .service(\n web::resource(\"/terminate\")\n .route(web::get().to(user::terminate_two_factor_auth)),\n ),\n );\n\n route = route.service(\n web::scope(\"/auth\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user::create_user_authentication_method))\n .route(web::put().to(user::update_user_authentication_method)),\n )\n .service(\n web::resource(\"/list\")\n .route(web::get().to(user::list_user_authentication_methods)),\n )\n .service(web::resource(\"/url\").route(web::get().to(user::get_sso_auth_url)))\n .service(\n web::resource(\"/select\").route(web::post().to(user::terminate_auth_select)),\n ),\n );\n\n #[cfg(feature = \"email\")]\n {\n route = route\n .service(web::resource(\"/from_email\").route(web::post().to(user::user_from_email)))\n .service(\n web::resource(\"/connect_account\")\n .route(web::post().to(user::user_connect_account)),\n )\n .service(\n web::resource(\"/forgot_password\").route(web::post().to(user::forgot_password)),\n )\n .service(\n web::resource(\"/reset_password\").route(web::post().to(user::reset_password)),\n )\n .service(\n web::resource(\"/signup_with_merchant_id\")\n .route(web::post().to(user::user_signup_with_merchant_id)),\n )\n .service(web::resource(\"/verify_email\").route(web::post().to(user::verify_email)))\n .service(\n web::resource(\"/v2/verify_email\").route(web::post().to(user::verify_email)),\n )\n .service(\n web::resource(\"/verify_email_request\")\n .route(web::post().to(user::verify_email_request)),\n )\n .service(\n web::resource(\"/user/resend_invite\").route(web::post().to(user::resend_invite)),\n )\n .service(\n web::resource(\"/accept_invite_from_email\")\n .route(web::post().to(user::accept_invite_from_email)),\n );\n }\n #[cfg(not(feature = \"email\"))]\n {\n route = route.service(web::resource(\"/signup\").route(web::post().to(user::user_signup)))\n }\n\n // User management\n route = route.service(\n web::scope(\"/user\")\n .service(web::resource(\"\").route(web::post().to(user::list_user_roles_details)))\n // TODO: To be deprecated\n .service(web::resource(\"/v2\").route(web::post().to(user::list_user_roles_details)))\n .service(\n web::resource(\"/list\").route(web::get().to(user_role::list_users_in_lineage)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_users_in_lineage)),\n )\n .service(\n web::resource(\"/invite_multiple\")\n .route(web::post().to(user::invite_multiple_user)),\n )\n .service(\n web::scope(\"/invite/accept\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\")\n .route(web::post().to(user_role::accept_invitations_pre_auth)),\n )\n .service(\n web::scope(\"/v2\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\").route(\n web::post().to(user_role::accept_invitations_pre_auth),\n ),\n ),\n ),\n )\n .service(\n web::resource(\"/update_role\")\n .route(web::post().to(user_role::update_user_role)),\n )\n .service(\n web::resource(\"/delete\").route(web::delete().to(user_role::delete_user_role)),\n ),\n );\n\n // Role information\n route =\n route.service(\n web::scope(\"/role\")\n .service(\n web::resource(\"\")\n .route(web::get().to(user_role::get_role_from_token))\n .route(web::post().to(user_role::create_role)),\n )\n .service(web::resource(\"/v2\").route(\n web::get().to(user_role::get_groups_and_resources_for_role_from_token),\n ))\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_roles_with_info)),\n )\n .service(\n web::scope(\"/list\")\n .service(\n web::resource(\"\")\n .route(web::get().to(user_role::list_roles_with_info)),\n )\n .service(web::resource(\"/invite\").route(\n web::get().to(user_role::list_invitable_roles_at_entity_level),\n ))\n .service(web::resource(\"/update\").route(\n web::get().to(user_role::list_updatable_roles_at_entity_level),\n )),\n )\n .service(\n web::resource(\"/{role_id}\")\n .route(web::get().to(user_role::get_role))\n .route(web::put().to(user_role::update_role)),\n )\n .service(\n web::resource(\"/{role_id}/v2\")\n .route(web::get().to(user_role::get_parent_info_for_role)),\n ),\n );\n\n #[cfg(feature = \"dummy_connector\")]\n {\n route = route.service(\n web::resource(\"/sample_data\")\n .route(web::post().to(user::generate_sample_data))\n .route(web::delete().to(user::delete_sample_data)),\n )\n }\n route\n }",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " .service(web::resource(\"/verify_email\").route(web::post().to(user::verify_email)))\n .service(\n web::resource(\"/v2/verify-email\").route(web::post().to(user::verify_email)),\n )\n .service(\n web::resource(\"/verify_email_request\")\n .route(web::post().to(user::verify_email_request)),\n )\n .service(\n web::resource(\"/user/resend_invite\").route(web::post().to(user::resend_invite)),\n )\n .service(\n web::resource(\"/accept_invite_from_email\")\n .route(web::post().to(user::accept_invite_from_email)),\n );\n }\n #[cfg(not(feature = \"email\"))]\n {\n route = route.service(web::resource(\"/signup\").route(web::post().to(user::user_signup)))\n }\n\n // User management\n route = route.service(\n web::scope(\"/user\")\n .service(web::resource(\"\").route(web::post().to(user::list_user_roles_details)))\n // TODO: To be deprecated\n .service(web::resource(\"/v2\").route(web::post().to(user::list_user_roles_details)))\n .service(\n web::resource(\"/list\").route(web::get().to(user_role::list_users_in_lineage)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_users_in_lineage)),\n )\n .service(\n web::resource(\"/invite_multiple\")\n .route(web::post().to(user::invite_multiple_user)),\n )\n .service(\n web::scope(\"/invite/accept\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\")\n .route(web::post().to(user_role::accept_invitations_pre_auth)),\n )\n .service(\n web::scope(\"/v2\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre-auth\").route(\n web::post().to(user_role::accept_invitations_pre_auth),\n ),",
|
| 19 |
+
"after": " .service(web::resource(\"/verify_email\").route(web::post().to(user::verify_email)))\n .service(\n web::resource(\"/v2/verify_email\").route(web::post().to(user::verify_email)),\n )\n .service(\n web::resource(\"/verify_email_request\")\n .route(web::post().to(user::verify_email_request)),\n )\n .service(\n web::resource(\"/user/resend_invite\").route(web::post().to(user::resend_invite)),\n )\n .service(\n web::resource(\"/accept_invite_from_email\")\n .route(web::post().to(user::accept_invite_from_email)),\n );\n }\n #[cfg(not(feature = \"email\"))]\n {\n route = route.service(web::resource(\"/signup\").route(web::post().to(user::user_signup)))\n }\n\n // User management\n route = route.service(\n web::scope(\"/user\")\n .service(web::resource(\"\").route(web::post().to(user::list_user_roles_details)))\n // TODO: To be deprecated\n .service(web::resource(\"/v2\").route(web::post().to(user::list_user_roles_details)))\n .service(\n web::resource(\"/list\").route(web::get().to(user_role::list_users_in_lineage)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_users_in_lineage)),\n )\n .service(\n web::resource(\"/invite_multiple\")\n .route(web::post().to(user::invite_multiple_user)),\n )\n .service(\n web::scope(\"/invite/accept\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\")\n .route(web::post().to(user_role::accept_invitations_pre_auth)),\n )\n .service(\n web::scope(\"/v2\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\").route(\n web::post().to(user_role::accept_invitations_pre_auth),\n ),"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "244303420401898cdfdb2ce0ac872889c55452b2"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/router/src/routes/app.rs::impl::User",
|
| 25 |
+
"file": "crates/router/src/routes/app.rs",
|
| 26 |
+
"kind": "impl_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "impl User {\n pub fn server(state: AppState) -> Scope {\n let mut route = web::scope(\"/user\").app_data(web::Data::new(state));\n\n route = route\n .service(web::resource(\"\").route(web::get().to(user::get_user_details)))\n .service(web::resource(\"/signin\").route(web::post().to(user::user_signin)))\n .service(web::resource(\"/v2/signin\").route(web::post().to(user::user_signin)))\n // signin/signup with sso using openidconnect\n .service(web::resource(\"/oidc\").route(web::post().to(user::sso_sign)))\n .service(web::resource(\"/signout\").route(web::post().to(user::signout)))\n .service(web::resource(\"/rotate_password\").route(web::post().to(user::rotate_password)))\n .service(web::resource(\"/change_password\").route(web::post().to(user::change_password)))\n .service(\n web::resource(\"/internal_signup\").route(web::post().to(user::internal_user_signup)),\n )\n .service(\n web::resource(\"/create_merchant\")\n .route(web::post().to(user::user_merchant_account_create)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/permission_info\")\n .route(web::get().to(user_role::get_authorization_info)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/module/list\").route(web::get().to(user_role::get_role_information)),\n )\n .service(\n web::resource(\"/parent/list\")\n .route(web::get().to(user_role::get_parent_group_info)),\n )\n .service(\n web::resource(\"/update\").route(web::post().to(user::update_user_account_details)),\n )\n .service(\n web::resource(\"/data\")\n .route(web::get().to(user::get_multiple_dashboard_metadata))\n .route(web::post().to(user::set_dashboard_metadata)),\n );\n\n route = route\n .service(web::scope(\"/key\").service(\n web::resource(\"/transfer\").route(web::post().to(user::transfer_user_key)),\n ));\n\n route = route.service(\n web::scope(\"/list\")\n .service(web::resource(\"/org\").route(web::get().to(user::list_orgs_for_user)))\n .service(\n web::resource(\"/merchant\")\n .route(web::get().to(user::list_merchants_for_user_in_org)),\n )\n .service(\n web::resource(\"/profile\")\n .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),\n )\n .service(\n web::resource(\"/invitation\")\n .route(web::get().to(user_role::list_invitations_for_user)),\n ),\n );\n\n route = route.service(\n web::scope(\"/switch\")\n .service(web::resource(\"/org\").route(web::post().to(user::switch_org_for_user)))\n .service(\n web::resource(\"/merchant\")\n .route(web::post().to(user::switch_merchant_for_user_in_org)),\n )\n .service(\n web::resource(\"/profile\")\n .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),\n ),\n );\n\n // Two factor auth routes\n route = route.service(\n web::scope(\"/2fa\")\n // TODO: to be deprecated\n .service(web::resource(\"\").route(web::get().to(user::check_two_factor_auth_status)))\n .service(\n web::resource(\"/v2\")\n .route(web::get().to(user::check_two_factor_auth_status_with_attempts)),\n )\n .service(\n web::scope(\"/totp\")\n .service(web::resource(\"/begin\").route(web::get().to(user::totp_begin)))\n .service(web::resource(\"/reset\").route(web::get().to(user::totp_reset)))\n .service(\n web::resource(\"/verify\")\n .route(web::post().to(user::totp_verify))\n .route(web::put().to(user::totp_update)),\n ),\n )\n .service(\n web::scope(\"/recovery_code\")\n .service(\n web::resource(\"/verify\")\n .route(web::post().to(user::verify_recovery_code)),\n )\n .service(\n web::resource(\"/generate\")\n .route(web::get().to(user::generate_recovery_codes)),\n ),\n )\n .service(\n web::resource(\"/terminate\")\n .route(web::get().to(user::terminate_two_factor_auth)),\n ),\n );\n\n route = route.service(\n web::scope(\"/auth\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user::create_user_authentication_method))\n .route(web::put().to(user::update_user_authentication_method)),\n )\n .service(\n web::resource(\"/list\")\n .route(web::get().to(user::list_user_authentication_methods)),\n )\n .service(web::resource(\"/url\").route(web::get().to(user::get_sso_auth_url)))\n .service(\n web::resource(\"/select\").route(web::post().to(user::terminate_auth_select)),\n ),\n );\n\n #[cfg(feature = \"email\")]\n {\n route = route\n .service(web::resource(\"/from_email\").route(web::post().to(user::user_from_email)))\n .service(\n web::resource(\"/connect_account\")\n .route(web::post().to(user::user_connect_account)),\n )\n .service(\n web::resource(\"/forgot_password\").route(web::post().to(user::forgot_password)),\n )\n .service(\n web::resource(\"/reset_password\").route(web::post().to(user::reset_password)),\n )\n .service(\n web::resource(\"/signup_with_merchant_id\")\n .route(web::post().to(user::user_signup_with_merchant_id)),\n )\n .service(web::resource(\"/verify_email\").route(web::post().to(user::verify_email)))\n .service(\n web::resource(\"/v2/verify-email\").route(web::post().to(user::verify_email)),\n )\n .service(\n web::resource(\"/verify_email_request\")\n .route(web::post().to(user::verify_email_request)),\n )\n .service(\n web::resource(\"/user/resend_invite\").route(web::post().to(user::resend_invite)),\n )\n .service(\n web::resource(\"/accept_invite_from_email\")\n .route(web::post().to(user::accept_invite_from_email)),\n );\n }\n #[cfg(not(feature = \"email\"))]\n {\n route = route.service(web::resource(\"/signup\").route(web::post().to(user::user_signup)))\n }\n\n // User management\n route = route.service(\n web::scope(\"/user\")\n .service(web::resource(\"\").route(web::post().to(user::list_user_roles_details)))\n // TODO: To be deprecated\n .service(web::resource(\"/v2\").route(web::post().to(user::list_user_roles_details)))\n .service(\n web::resource(\"/list\").route(web::get().to(user_role::list_users_in_lineage)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_users_in_lineage)),\n )\n .service(\n web::resource(\"/invite_multiple\")\n .route(web::post().to(user::invite_multiple_user)),\n )\n .service(\n web::scope(\"/invite/accept\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\")\n .route(web::post().to(user_role::accept_invitations_pre_auth)),\n )\n .service(\n web::scope(\"/v2\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre-auth\").route(\n web::post().to(user_role::accept_invitations_pre_auth),\n ),\n ),\n ),\n )\n .service(\n web::resource(\"/update_role\")\n .route(web::post().to(user_role::update_user_role)),\n )\n .service(\n web::resource(\"/delete\").route(web::delete().to(user_role::delete_user_role)),\n ),\n );\n\n // Role information\n route =\n route.service(\n web::scope(\"/role\")\n .service(\n web::resource(\"\")\n .route(web::get().to(user_role::get_role_from_token))\n .route(web::post().to(user_role::create_role)),\n )\n .service(web::resource(\"/v2\").route(\n web::get().to(user_role::get_groups_and_resources_for_role_from_token),\n ))\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_roles_with_info)),\n )\n .service(\n web::scope(\"/list\")\n .service(\n web::resource(\"\")\n .route(web::get().to(user_role::list_roles_with_info)),\n )\n .service(web::resource(\"/invite\").route(\n web::get().to(user_role::list_invitable_roles_at_entity_level),\n ))\n .service(web::resource(\"/update\").route(\n web::get().to(user_role::list_updatable_roles_at_entity_level),\n )),\n )\n .service(\n web::resource(\"/{role_id}\")\n .route(web::get().to(user_role::get_role))\n .route(web::put().to(user_role::update_role)),\n )\n .service(\n web::resource(\"/{role_id}/v2\")\n .route(web::get().to(user_role::get_parent_info_for_role)),\n ),\n );\n\n #[cfg(feature = \"dummy_connector\")]\n {\n route = route.service(\n web::resource(\"/sample_data\")\n .route(web::post().to(user::generate_sample_data))\n .route(web::delete().to(user::delete_sample_data)),\n )\n }\n route\n }\n}",
|
| 31 |
+
"after_code": "impl User {\n pub fn server(state: AppState) -> Scope {\n let mut route = web::scope(\"/user\").app_data(web::Data::new(state));\n\n route = route\n .service(web::resource(\"\").route(web::get().to(user::get_user_details)))\n .service(web::resource(\"/signin\").route(web::post().to(user::user_signin)))\n .service(web::resource(\"/v2/signin\").route(web::post().to(user::user_signin)))\n // signin/signup with sso using openidconnect\n .service(web::resource(\"/oidc\").route(web::post().to(user::sso_sign)))\n .service(web::resource(\"/signout\").route(web::post().to(user::signout)))\n .service(web::resource(\"/rotate_password\").route(web::post().to(user::rotate_password)))\n .service(web::resource(\"/change_password\").route(web::post().to(user::change_password)))\n .service(\n web::resource(\"/internal_signup\").route(web::post().to(user::internal_user_signup)),\n )\n .service(\n web::resource(\"/create_merchant\")\n .route(web::post().to(user::user_merchant_account_create)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/permission_info\")\n .route(web::get().to(user_role::get_authorization_info)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/module/list\").route(web::get().to(user_role::get_role_information)),\n )\n .service(\n web::resource(\"/parent/list\")\n .route(web::get().to(user_role::get_parent_group_info)),\n )\n .service(\n web::resource(\"/update\").route(web::post().to(user::update_user_account_details)),\n )\n .service(\n web::resource(\"/data\")\n .route(web::get().to(user::get_multiple_dashboard_metadata))\n .route(web::post().to(user::set_dashboard_metadata)),\n );\n\n route = route\n .service(web::scope(\"/key\").service(\n web::resource(\"/transfer\").route(web::post().to(user::transfer_user_key)),\n ));\n\n route = route.service(\n web::scope(\"/list\")\n .service(web::resource(\"/org\").route(web::get().to(user::list_orgs_for_user)))\n .service(\n web::resource(\"/merchant\")\n .route(web::get().to(user::list_merchants_for_user_in_org)),\n )\n .service(\n web::resource(\"/profile\")\n .route(web::get().to(user::list_profiles_for_user_in_org_and_merchant)),\n )\n .service(\n web::resource(\"/invitation\")\n .route(web::get().to(user_role::list_invitations_for_user)),\n ),\n );\n\n route = route.service(\n web::scope(\"/switch\")\n .service(web::resource(\"/org\").route(web::post().to(user::switch_org_for_user)))\n .service(\n web::resource(\"/merchant\")\n .route(web::post().to(user::switch_merchant_for_user_in_org)),\n )\n .service(\n web::resource(\"/profile\")\n .route(web::post().to(user::switch_profile_for_user_in_org_and_merchant)),\n ),\n );\n\n // Two factor auth routes\n route = route.service(\n web::scope(\"/2fa\")\n // TODO: to be deprecated\n .service(web::resource(\"\").route(web::get().to(user::check_two_factor_auth_status)))\n .service(\n web::resource(\"/v2\")\n .route(web::get().to(user::check_two_factor_auth_status_with_attempts)),\n )\n .service(\n web::scope(\"/totp\")\n .service(web::resource(\"/begin\").route(web::get().to(user::totp_begin)))\n .service(web::resource(\"/reset\").route(web::get().to(user::totp_reset)))\n .service(\n web::resource(\"/verify\")\n .route(web::post().to(user::totp_verify))\n .route(web::put().to(user::totp_update)),\n ),\n )\n .service(\n web::scope(\"/recovery_code\")\n .service(\n web::resource(\"/verify\")\n .route(web::post().to(user::verify_recovery_code)),\n )\n .service(\n web::resource(\"/generate\")\n .route(web::get().to(user::generate_recovery_codes)),\n ),\n )\n .service(\n web::resource(\"/terminate\")\n .route(web::get().to(user::terminate_two_factor_auth)),\n ),\n );\n\n route = route.service(\n web::scope(\"/auth\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user::create_user_authentication_method))\n .route(web::put().to(user::update_user_authentication_method)),\n )\n .service(\n web::resource(\"/list\")\n .route(web::get().to(user::list_user_authentication_methods)),\n )\n .service(web::resource(\"/url\").route(web::get().to(user::get_sso_auth_url)))\n .service(\n web::resource(\"/select\").route(web::post().to(user::terminate_auth_select)),\n ),\n );\n\n #[cfg(feature = \"email\")]\n {\n route = route\n .service(web::resource(\"/from_email\").route(web::post().to(user::user_from_email)))\n .service(\n web::resource(\"/connect_account\")\n .route(web::post().to(user::user_connect_account)),\n )\n .service(\n web::resource(\"/forgot_password\").route(web::post().to(user::forgot_password)),\n )\n .service(\n web::resource(\"/reset_password\").route(web::post().to(user::reset_password)),\n )\n .service(\n web::resource(\"/signup_with_merchant_id\")\n .route(web::post().to(user::user_signup_with_merchant_id)),\n )\n .service(web::resource(\"/verify_email\").route(web::post().to(user::verify_email)))\n .service(\n web::resource(\"/v2/verify_email\").route(web::post().to(user::verify_email)),\n )\n .service(\n web::resource(\"/verify_email_request\")\n .route(web::post().to(user::verify_email_request)),\n )\n .service(\n web::resource(\"/user/resend_invite\").route(web::post().to(user::resend_invite)),\n )\n .service(\n web::resource(\"/accept_invite_from_email\")\n .route(web::post().to(user::accept_invite_from_email)),\n );\n }\n #[cfg(not(feature = \"email\"))]\n {\n route = route.service(web::resource(\"/signup\").route(web::post().to(user::user_signup)))\n }\n\n // User management\n route = route.service(\n web::scope(\"/user\")\n .service(web::resource(\"\").route(web::post().to(user::list_user_roles_details)))\n // TODO: To be deprecated\n .service(web::resource(\"/v2\").route(web::post().to(user::list_user_roles_details)))\n .service(\n web::resource(\"/list\").route(web::get().to(user_role::list_users_in_lineage)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_users_in_lineage)),\n )\n .service(\n web::resource(\"/invite_multiple\")\n .route(web::post().to(user::invite_multiple_user)),\n )\n .service(\n web::scope(\"/invite/accept\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\")\n .route(web::post().to(user_role::accept_invitations_pre_auth)),\n )\n .service(\n web::scope(\"/v2\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\").route(\n web::post().to(user_role::accept_invitations_pre_auth),\n ),\n ),\n ),\n )\n .service(\n web::resource(\"/update_role\")\n .route(web::post().to(user_role::update_user_role)),\n )\n .service(\n web::resource(\"/delete\").route(web::delete().to(user_role::delete_user_role)),\n ),\n );\n\n // Role information\n route =\n route.service(\n web::scope(\"/role\")\n .service(\n web::resource(\"\")\n .route(web::get().to(user_role::get_role_from_token))\n .route(web::post().to(user_role::create_role)),\n )\n .service(web::resource(\"/v2\").route(\n web::get().to(user_role::get_groups_and_resources_for_role_from_token),\n ))\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_roles_with_info)),\n )\n .service(\n web::scope(\"/list\")\n .service(\n web::resource(\"\")\n .route(web::get().to(user_role::list_roles_with_info)),\n )\n .service(web::resource(\"/invite\").route(\n web::get().to(user_role::list_invitable_roles_at_entity_level),\n ))\n .service(web::resource(\"/update\").route(\n web::get().to(user_role::list_updatable_roles_at_entity_level),\n )),\n )\n .service(\n web::resource(\"/{role_id}\")\n .route(web::get().to(user_role::get_role))\n .route(web::put().to(user_role::update_role)),\n )\n .service(\n web::resource(\"/{role_id}/v2\")\n .route(web::get().to(user_role::get_parent_info_for_role)),\n ),\n );\n\n #[cfg(feature = \"dummy_connector\")]\n {\n route = route.service(\n web::resource(\"/sample_data\")\n .route(web::post().to(user::generate_sample_data))\n .route(web::delete().to(user::delete_sample_data)),\n )\n }\n route\n }\n}",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " .service(web::resource(\"/verify_email\").route(web::post().to(user::verify_email)))\n .service(\n web::resource(\"/v2/verify-email\").route(web::post().to(user::verify_email)),\n )\n .service(\n web::resource(\"/verify_email_request\")\n .route(web::post().to(user::verify_email_request)),\n )\n .service(\n web::resource(\"/user/resend_invite\").route(web::post().to(user::resend_invite)),\n )\n .service(\n web::resource(\"/accept_invite_from_email\")\n .route(web::post().to(user::accept_invite_from_email)),\n );\n }\n #[cfg(not(feature = \"email\"))]\n {\n route = route.service(web::resource(\"/signup\").route(web::post().to(user::user_signup)))\n }\n\n // User management\n route = route.service(\n web::scope(\"/user\")\n .service(web::resource(\"\").route(web::post().to(user::list_user_roles_details)))\n // TODO: To be deprecated\n .service(web::resource(\"/v2\").route(web::post().to(user::list_user_roles_details)))\n .service(\n web::resource(\"/list\").route(web::get().to(user_role::list_users_in_lineage)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_users_in_lineage)),\n )\n .service(\n web::resource(\"/invite_multiple\")\n .route(web::post().to(user::invite_multiple_user)),\n )\n .service(\n web::scope(\"/invite/accept\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\")\n .route(web::post().to(user_role::accept_invitations_pre_auth)),\n )\n .service(\n web::scope(\"/v2\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre-auth\").route(\n web::post().to(user_role::accept_invitations_pre_auth),\n ),",
|
| 34 |
+
"after": " .service(web::resource(\"/verify_email\").route(web::post().to(user::verify_email)))\n .service(\n web::resource(\"/v2/verify_email\").route(web::post().to(user::verify_email)),\n )\n .service(\n web::resource(\"/verify_email_request\")\n .route(web::post().to(user::verify_email_request)),\n )\n .service(\n web::resource(\"/user/resend_invite\").route(web::post().to(user::resend_invite)),\n )\n .service(\n web::resource(\"/accept_invite_from_email\")\n .route(web::post().to(user::accept_invite_from_email)),\n );\n }\n #[cfg(not(feature = \"email\"))]\n {\n route = route.service(web::resource(\"/signup\").route(web::post().to(user::user_signup)))\n }\n\n // User management\n route = route.service(\n web::scope(\"/user\")\n .service(web::resource(\"\").route(web::post().to(user::list_user_roles_details)))\n // TODO: To be deprecated\n .service(web::resource(\"/v2\").route(web::post().to(user::list_user_roles_details)))\n .service(\n web::resource(\"/list\").route(web::get().to(user_role::list_users_in_lineage)),\n )\n // TODO: To be deprecated\n .service(\n web::resource(\"/v2/list\")\n .route(web::get().to(user_role::list_users_in_lineage)),\n )\n .service(\n web::resource(\"/invite_multiple\")\n .route(web::post().to(user::invite_multiple_user)),\n )\n .service(\n web::scope(\"/invite/accept\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\")\n .route(web::post().to(user_role::accept_invitations_pre_auth)),\n )\n .service(\n web::scope(\"/v2\")\n .service(\n web::resource(\"\")\n .route(web::post().to(user_role::accept_invitations_v2)),\n )\n .service(\n web::resource(\"/pre_auth\").route(\n web::post().to(user_role::accept_invitations_pre_auth),\n ),"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "244303420401898cdfdb2ce0ac872889c55452b2"
|
| 37 |
+
}
|
| 38 |
+
]
|
| 39 |
+
}
|
diffs/pr_6761/01907d5/diff.json
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "01907d50f30e8a9a5015851168c44e1999fd16cc",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/openapi/src/openapi.rs",
|
| 6 |
+
"crates/openapi/src/routes/routing.rs"
|
| 7 |
+
],
|
| 8 |
+
"diffs": [
|
| 9 |
+
{
|
| 10 |
+
"id": "crates/openapi/src/routes/routing.rs::function::contract_based_routing_update_configs",
|
| 11 |
+
"file": "crates/openapi/src/routes/routing.rs",
|
| 12 |
+
"kind": "function_item",
|
| 13 |
+
"status": "added",
|
| 14 |
+
"before_code": null,
|
| 15 |
+
"after_code": "pub async fn contract_based_routing_update_configs() {}",
|
| 16 |
+
"diff_span": null,
|
| 17 |
+
"commit_sha": "01907d50f30e8a9a5015851168c44e1999fd16cc"
|
| 18 |
+
},
|
| 19 |
+
{
|
| 20 |
+
"id": "crates/openapi/src/routes/routing.rs::function::contract_based_routing_setup_config",
|
| 21 |
+
"file": "crates/openapi/src/routes/routing.rs",
|
| 22 |
+
"kind": "function_item",
|
| 23 |
+
"status": "added",
|
| 24 |
+
"before_code": null,
|
| 25 |
+
"after_code": "pub async fn contract_based_routing_setup_config() {}",
|
| 26 |
+
"diff_span": null,
|
| 27 |
+
"commit_sha": "01907d50f30e8a9a5015851168c44e1999fd16cc"
|
| 28 |
+
}
|
| 29 |
+
]
|
| 30 |
+
}
|
diffs/pr_6761/025f70c/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_6761/063d978/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_6761/0a5c5e1/diff.json
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "0a5c5e19428579131ca289dd75d952eab1e90f80",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 6 |
+
"crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs",
|
| 7 |
+
"crates/router/src/core/payments/routing.rs",
|
| 8 |
+
"crates/router/src/core/routing.rs",
|
| 9 |
+
"crates/router/src/core/routing/helpers.rs"
|
| 10 |
+
],
|
| 11 |
+
"diffs": [
|
| 12 |
+
{
|
| 13 |
+
"id": "crates/router/src/core/routing/helpers.rs::function::push_metrics_with_update_window_for_contract_based_routing",
|
| 14 |
+
"file": "crates/router/src/core/routing/helpers.rs",
|
| 15 |
+
"kind": "function_item",
|
| 16 |
+
"status": "modified",
|
| 17 |
+
"code_changed": true,
|
| 18 |
+
"imports_changed": false,
|
| 19 |
+
"before_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ]),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 20 |
+
"after_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n // let payment_status_attribute =\n // get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ]),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 21 |
+
"diff_span": {
|
| 22 |
+
"before": " routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores",
|
| 23 |
+
"after": " routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n // let payment_status_attribute =\n // get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores"
|
| 24 |
+
},
|
| 25 |
+
"commit_sha": "0a5c5e19428579131ca289dd75d952eab1e90f80"
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"id": "crates/router/src/core/payments/routing.rs::function::perform_contract_based_routing",
|
| 29 |
+
"file": "crates/router/src/core/payments/routing.rs",
|
| 30 |
+
"kind": "function_item",
|
| 31 |
+
"status": "modified",
|
| 32 |
+
"code_changed": true,
|
| 33 |
+
"imports_changed": false,
|
| 34 |
+
"before_code": "pub async fn perform_contract_based_routing(\n state: &SessionState,\n routable_connectors: Vec<api_routing::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,\n contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,\n) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {\n if contract_based_algo_ref.enabled_feature\n == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection\n {\n logger::debug!(\n \"performing contract_based_routing for profile {}\",\n business_profile.get_id().get_string_repr()\n );\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .as_ref()\n .ok_or(errors::RoutingError::ContractRoutingClientInitializationError)\n .attach_printable(\"contract routing gRPC client not found\")?;\n\n let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<\n api_routing::ContractBasedRoutingConfig,\n >(\n state,\n business_profile,\n contract_based_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::RoutingError::GenericNotFoundError {\n field: \"contract_based_routing_algorithm_id\".to_string(),\n })\n .attach_printable(\n \"contract_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::RoutingError::ContractBasedRoutingConfigError)\n .attach_printable(\"unable to fetch contract based dynamic routing configs\")?;\n\n let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let contract_based_connectors: CalContractScoreResponse = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_configs,\n \"\".to_string(),\n routable_connectors,\n )\n .await\n .change_context(errors::RoutingError::ContractScoreCalculationError)\n .attach_printable(\n \"unable to calculate/fetch contract score from dynamic routing service\",\n )?;\n\n let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());\n\n for label_with_score in contract_based_connectors.labels_with_score {\n let (connector, merchant_connector_id) = label_with_score.label\n .split_once(':')\n .ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))\n .attach_printable(\n \"unable to split connector_name and mca_id from the label obtained by the dynamic routing service\",\n )?;\n\n connectors.push(api_routing::RoutableConnectorChoice {\n choice_kind: api_routing::RoutableChoiceKind::FullStruct,\n connector: common_enums::RoutableConnectors::from_str(connector)\n .change_context(errors::RoutingError::GenericConversionError {\n from: \"String\".to_string(),\n to: \"RoutableConnectors\".to_string(),\n })\n .attach_printable(\"unable to convert String to RoutableConnectors\")?,\n merchant_connector_id: Some(\n common_utils::id_type::MerchantConnectorAccountId::wrap(\n merchant_connector_id.to_string(),\n )\n .change_context(errors::RoutingError::GenericConversionError {\n from: \"String\".to_string(),\n to: \"MerchantConnectorAccountId\".to_string(),\n })\n .attach_printable(\"unable to convert MerchantConnectorAccountId from string\")?,\n ),\n });\n }\n\n logger::debug!(contract_based_routing_connectors=?connectors);\n Ok(connectors)\n } else {\n Ok(routable_connectors)\n }\n}",
|
| 35 |
+
"after_code": "pub async fn perform_contract_based_routing(\n state: &SessionState,\n routable_connectors: Vec<api_routing::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,\n contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,\n) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {\n if contract_based_algo_ref.enabled_feature\n == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection\n {\n logger::debug!(\n \"performing contract_based_routing for profile {}\",\n business_profile.get_id().get_string_repr()\n );\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .as_ref()\n .ok_or(errors::RoutingError::ContractRoutingClientInitializationError)\n .attach_printable(\"contract routing gRPC client not found\")?;\n\n let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<\n api_routing::ContractBasedRoutingConfig,\n >(\n state,\n business_profile,\n contract_based_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::RoutingError::GenericNotFoundError {\n field: \"contract_based_routing_algorithm_id\".to_string(),\n })\n .attach_printable(\n \"contract_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::RoutingError::ContractBasedRoutingConfigError)\n .attach_printable(\"unable to fetch contract based dynamic routing configs\")?;\n\n let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let contract_based_connectors: CalContractScoreResponse = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_configs,\n \"\".to_string(),\n routable_connectors,\n )\n .await\n .change_context(errors::RoutingError::ContractScoreCalculationError)\n .attach_printable(\n \"unable to calculate/fetch contract score from dynamic routing service\",\n )?;\n\n let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());\n\n for label_with_score in contract_based_connectors.labels_with_score {\n let (connector, merchant_connector_id) = label_with_score.label\n .split_once(':')\n .ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))\n .attach_printable(\n \"unable to split connector_name and mca_id from the label obtained by the dynamic routing service\",\n )?;\n\n connectors.push(api_routing::RoutableConnectorChoice {\n choice_kind: api_routing::RoutableChoiceKind::FullStruct,\n connector: common_enums::RoutableConnectors::from_str(connector)\n .change_context(errors::RoutingError::GenericConversionError {\n from: \"String\".to_string(),\n to: \"RoutableConnectors\".to_string(),\n })\n .attach_printable(\"unable to convert String to RoutableConnectors\")?,\n merchant_connector_id: Some(\n common_utils::id_type::MerchantConnectorAccountId::wrap(\n merchant_connector_id.to_string(),\n )\n .change_context(errors::RoutingError::GenericConversionError {\n from: \"String\".to_string(),\n to: \"MerchantConnectorAccountId\".to_string(),\n })\n .attach_printable(\"unable to convert MerchantConnectorAccountId from string\")?,\n ),\n });\n }\n\n logger::debug!(contract_based_routing_connectors=?connectors);\n Ok(connectors)\n } else {\n Ok(routable_connectors)\n }\n}",
|
| 36 |
+
"diff_span": {
|
| 37 |
+
"before": " routable_connectors: Vec<api_routing::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,\n contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,\n) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {",
|
| 38 |
+
"after": " routable_connectors: Vec<api_routing::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,\n contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,\n) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {"
|
| 39 |
+
},
|
| 40 |
+
"commit_sha": "0a5c5e19428579131ca289dd75d952eab1e90f80"
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs::trait::ContractBasedDynamicRouting",
|
| 44 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs",
|
| 45 |
+
"kind": "trait_item",
|
| 46 |
+
"status": "modified",
|
| 47 |
+
"code_changed": true,
|
| 48 |
+
"imports_changed": false,
|
| 49 |
+
"before_code": "pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {\n /// To calculate the contract scores for the list of chosen connectors\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n ) -> DynamicRoutingResult<CalContractScoreResponse>;\n /// To update the contract scores with the given labels\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse>;\n /// To invalidates the contract scores agaisnt the id\n async fn invalidate_contracts(\n &self,\n id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse>;\n}",
|
| 50 |
+
"after_code": "pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {\n /// To calculate the contract scores for the list of chosen connectors\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n ) -> DynamicRoutingResult<CalContractScoreResponse>;\n /// To update the contract scores with the given labels\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse>;\n /// To invalidates the contract scores against the id\n async fn invalidate_contracts(\n &self,\n id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse>;\n}",
|
| 51 |
+
"diff_span": {
|
| 52 |
+
"before": " response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse>;\n /// To invalidates the contract scores agaisnt the id\n async fn invalidate_contracts(\n &self,",
|
| 53 |
+
"after": " response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse>;\n /// To invalidates the contract scores against the id\n async fn invalidate_contracts(\n &self,"
|
| 54 |
+
},
|
| 55 |
+
"commit_sha": "0a5c5e19428579131ca289dd75d952eab1e90f80"
|
| 56 |
+
},
|
| 57 |
+
{
|
| 58 |
+
"id": "crates/router/src/core/routing.rs::function::contract_based_dynamic_routing_setup",
|
| 59 |
+
"file": "crates/router/src/core/routing.rs",
|
| 60 |
+
"kind": "function_item",
|
| 61 |
+
"status": "modified",
|
| 62 |
+
"code_changed": true,
|
| 63 |
+
"imports_changed": false,
|
| 64 |
+
"before_code": "pub async fn contract_based_dynamic_routing_setup(\n state: SessionState,\n key_store: domain::MerchantKeyStore,\n merchant_account: domain::MerchantAccount,\n profile_id: common_utils::id_type::ProfileId,\n feature_to_enable: routing_types::DynamicRoutingFeatures,\n config: routing_types::ContractBasedRoutingConfig,\n) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> {\n let db = state.store.as_ref();\n let key_manager_state = &(&state).into();\n\n let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n Some(&profile_id),\n merchant_account.get_id(),\n )\n .await?\n .get_required_value(\"Profile\")\n .change_context(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n // validate the contained mca_ids\n if let Some(info_vec) = &config.label_info {\n for info in info_vec {\n let mca = db\n .find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n key_manager_state,\n merchant_account.get_id(),\n &info.mca_id,\n &key_store,\n )\n .await\n .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: info.mca_id.get_string_repr().to_owned(),\n })?;\n\n utils::when(&mca.connector_name != &info.label, || {\n Err(errors::ApiErrorResponse::InvalidRequestData {\n message: \"Incorrect mca configuration recieved\".to_string(),\n })\n })?;\n }\n }\n\n let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize dynamic routing algorithm ref from business profile\",\n )\n .ok()\n .flatten();\n\n utils::when(\n dynamic_routing_algo_ref\n .as_mut()\n .map(|algo| {\n algo.contract_based_routing.as_mut().map(|contract_algo| {\n *contract_algo.get_enabled_features() == feature_to_enable\n && contract_algo\n .clone()\n .get_algorithm_id_with_timestamp()\n .algorithm_id\n .is_some()\n })\n })\n .flatten()\n .unwrap_or(false),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Contract Routing with sepcified features is already enabled\".to_string(),\n })\n },\n )?;\n\n let merchant_id = business_profile.merchant_id.clone();\n let algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n\n let algo = RoutingAlgorithm {\n algorithm_id: algorithm_id.clone(),\n profile_id: profile_id.clone(),\n merchant_id,\n name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),\n description: None,\n kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,\n algorithm_data: serde_json::json!(config),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: common_enums::TransactionType::Payment,\n };\n\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based\n // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up\n let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref {\n algo.update_algorithm_id(\n algorithm_id,\n feature_to_enable,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n );\n algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting);\n algo\n } else {\n let contract_algo = routing_types::ContractRoutingAlgorithm {\n algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(algorithm_id.clone()),\n timestamp: common_utils::date_time::now_unix_timestamp(),\n },\n enabled_feature: feature_to_enable,\n };\n let dynamic_routing_algo_ref = routing_types::DynamicRoutingAlgorithmRef {\n success_based_algorithm: None,\n elimination_routing_algorithm: None,\n dynamic_routing_volume_split: None,\n contract_based_routing: Some(contract_algo),\n };\n dynamic_routing_algo_ref\n };\n\n match feature_to_enable {\n routing::DynamicRoutingFeatures::Metrics\n | routing::DynamicRoutingFeatures::DynamicConnectorSelection => {\n helpers::update_business_profile_active_dynamic_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n final_algorithm,\n )\n .await?;\n\n // Should we also update at dynamic routing service?\n let new_record = record.foreign_into();\n\n metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([(\"profile_id\", profile_id.get_string_repr().to_string())]),\n );\n Ok(service_api::ApplicationResponse::Json(new_record))\n }\n routing::DynamicRoutingFeatures::None => {\n helpers::disable_dynamic_routing_algorithm(\n &state,\n key_store,\n business_profile,\n final_algorithm,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n )\n .await\n }\n }\n}",
|
| 65 |
+
"after_code": "pub async fn contract_based_dynamic_routing_setup(\n state: SessionState,\n key_store: domain::MerchantKeyStore,\n merchant_account: domain::MerchantAccount,\n profile_id: common_utils::id_type::ProfileId,\n feature_to_enable: routing_types::DynamicRoutingFeatures,\n config: routing_types::ContractBasedRoutingConfig,\n) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> {\n let db = state.store.as_ref();\n let key_manager_state = &(&state).into();\n\n let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n Some(&profile_id),\n merchant_account.get_id(),\n )\n .await?\n .get_required_value(\"Profile\")\n .change_context(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n // validate the contained mca_ids\n if let Some(info_vec) = &config.label_info {\n for info in info_vec {\n let mca = db\n .find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n key_manager_state,\n merchant_account.get_id(),\n &info.mca_id,\n &key_store,\n )\n .await\n .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: info.mca_id.get_string_repr().to_owned(),\n })?;\n\n utils::when(&mca.connector_name != &info.label, || {\n Err(errors::ApiErrorResponse::InvalidRequestData {\n message: \"Incorrect mca configuration received\".to_string(),\n })\n })?;\n }\n }\n\n let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize dynamic routing algorithm ref from business profile\",\n )\n .ok()\n .flatten();\n\n utils::when(\n dynamic_routing_algo_ref\n .as_mut()\n .map(|algo| {\n algo.contract_based_routing.as_mut().map(|contract_algo| {\n *contract_algo.get_enabled_features() == feature_to_enable\n && contract_algo\n .clone()\n .get_algorithm_id_with_timestamp()\n .algorithm_id\n .is_some()\n })\n })\n .flatten()\n .unwrap_or(false),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Contract Routing with specified features is already enabled\".to_string(),\n })\n },\n )?;\n\n let merchant_id = business_profile.merchant_id.clone();\n let algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n\n let algo = RoutingAlgorithm {\n algorithm_id: algorithm_id.clone(),\n profile_id: profile_id.clone(),\n merchant_id,\n name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),\n description: None,\n kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,\n algorithm_data: serde_json::json!(config),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: common_enums::TransactionType::Payment,\n };\n\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based\n // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up\n let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref {\n algo.update_algorithm_id(\n algorithm_id,\n feature_to_enable,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n );\n algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting);\n algo\n } else {\n let contract_algo = routing_types::ContractRoutingAlgorithm {\n algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(algorithm_id.clone()),\n timestamp: common_utils::date_time::now_unix_timestamp(),\n },\n enabled_feature: feature_to_enable,\n };\n let dynamic_routing_algo_ref = routing_types::DynamicRoutingAlgorithmRef {\n success_based_algorithm: None,\n elimination_routing_algorithm: None,\n dynamic_routing_volume_split: None,\n contract_based_routing: Some(contract_algo),\n };\n dynamic_routing_algo_ref\n };\n\n match feature_to_enable {\n routing::DynamicRoutingFeatures::Metrics\n | routing::DynamicRoutingFeatures::DynamicConnectorSelection => {\n helpers::update_business_profile_active_dynamic_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n final_algorithm,\n )\n .await?;\n\n // Should we also update at dynamic routing service?\n let new_record = record.foreign_into();\n\n metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([(\"profile_id\", profile_id.get_string_repr().to_string())]),\n );\n Ok(service_api::ApplicationResponse::Json(new_record))\n }\n routing::DynamicRoutingFeatures::None => {\n helpers::disable_dynamic_routing_algorithm(\n &state,\n key_store,\n business_profile,\n final_algorithm,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n )\n .await\n }\n }\n}",
|
| 66 |
+
"diff_span": {
|
| 67 |
+
"before": " utils::when(&mca.connector_name != &info.label, || {\n Err(errors::ApiErrorResponse::InvalidRequestData {\n message: \"Incorrect mca configuration recieved\".to_string(),\n })\n })?;\n }\n }\n\n let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize dynamic routing algorithm ref from business profile\",\n )\n .ok()\n .flatten();\n\n utils::when(\n dynamic_routing_algo_ref\n .as_mut()\n .map(|algo| {\n algo.contract_based_routing.as_mut().map(|contract_algo| {\n *contract_algo.get_enabled_features() == feature_to_enable\n && contract_algo\n .clone()\n .get_algorithm_id_with_timestamp()\n .algorithm_id\n .is_some()\n })\n })\n .flatten()\n .unwrap_or(false),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Contract Routing with sepcified features is already enabled\".to_string(),\n })\n },",
|
| 68 |
+
"after": " utils::when(&mca.connector_name != &info.label, || {\n Err(errors::ApiErrorResponse::InvalidRequestData {\n message: \"Incorrect mca configuration received\".to_string(),\n })\n })?;\n }\n }\n\n let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize dynamic routing algorithm ref from business profile\",\n )\n .ok()\n .flatten();\n\n utils::when(\n dynamic_routing_algo_ref\n .as_mut()\n .map(|algo| {\n algo.contract_based_routing.as_mut().map(|contract_algo| {\n *contract_algo.get_enabled_features() == feature_to_enable\n && contract_algo\n .clone()\n .get_algorithm_id_with_timestamp()\n .algorithm_id\n .is_some()\n })\n })\n .flatten()\n .unwrap_or(false),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Contract Routing with specified features is already enabled\".to_string(),\n })\n },"
|
| 69 |
+
},
|
| 70 |
+
"commit_sha": "0a5c5e19428579131ca289dd75d952eab1e90f80"
|
| 71 |
+
},
|
| 72 |
+
{
|
| 73 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs::impl::CalContractScoreConfig",
|
| 74 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs",
|
| 75 |
+
"kind": "impl_item",
|
| 76 |
+
"status": "modified",
|
| 77 |
+
"code_changed": true,
|
| 78 |
+
"imports_changed": false,
|
| 79 |
+
"before_code": "impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig {\n type Error = error_stack::Report<DynamicRoutingError>;\n fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config\n .time_scale\n .clone()\n .map(|scale| TimeScale::foreign_from(scale)),\n })\n }\n}",
|
| 80 |
+
"after_code": "impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig {\n type Error = error_stack::Report<DynamicRoutingError>;\n fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config\n .time_scale\n .clone()\n .map(TimeScale::foreign_from),\n })\n }\n}",
|
| 81 |
+
"diff_span": {
|
| 82 |
+
"before": " .time_scale\n .clone()\n .map(|scale| TimeScale::foreign_from(scale)),\n })\n }",
|
| 83 |
+
"after": " .time_scale\n .clone()\n .map(TimeScale::foreign_from),\n })\n }"
|
| 84 |
+
},
|
| 85 |
+
"commit_sha": "0a5c5e19428579131ca289dd75d952eab1e90f80"
|
| 86 |
+
},
|
| 87 |
+
{
|
| 88 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs::CalContractScoreConfig::function::foreign_try_from",
|
| 89 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs",
|
| 90 |
+
"kind": "function_item",
|
| 91 |
+
"status": "modified",
|
| 92 |
+
"code_changed": true,
|
| 93 |
+
"imports_changed": false,
|
| 94 |
+
"before_code": "fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config\n .time_scale\n .clone()\n .map(|scale| TimeScale::foreign_from(scale)),\n })\n }",
|
| 95 |
+
"after_code": "fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config\n .time_scale\n .clone()\n .map(TimeScale::foreign_from),\n })\n }",
|
| 96 |
+
"diff_span": {
|
| 97 |
+
"before": " .time_scale\n .clone()\n .map(|scale| TimeScale::foreign_from(scale)),\n })\n }",
|
| 98 |
+
"after": " .time_scale\n .clone()\n .map(TimeScale::foreign_from),\n })\n }"
|
| 99 |
+
},
|
| 100 |
+
"commit_sha": "0a5c5e19428579131ca289dd75d952eab1e90f80"
|
| 101 |
+
}
|
| 102 |
+
]
|
| 103 |
+
}
|
diffs/pr_6761/0f4535b/diff.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "0f4535bfd86d75a24086219cd0af96c683f049b3",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/core/routing/helpers.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": []
|
| 8 |
+
}
|
diffs/pr_6761/130ce8e/diff.json
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "130ce8e1959868296156ecf9a013a4bdafb0553f",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/core/routing.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/router/src/core/routing.rs::function::link_routing_config",
|
| 10 |
+
"file": "crates/router/src/core/routing.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "pub async fn link_routing_config(\n state: SessionState,\n merchant_account: domain::MerchantAccount,\n key_store: domain::MerchantKeyStore,\n authentication_profile_id: Option<common_utils::id_type::ProfileId>,\n algorithm_id: common_utils::id_type::RoutingId,\n transaction_type: &enums::TransactionType,\n) -> RouterResponse<routing_types::RoutingDictionaryRecord> {\n metrics::ROUTING_LINK_CONFIG.add(1, &[]);\n let db = state.store.as_ref();\n let key_manager_state = &(&state).into();\n\n let routing_algorithm = db\n .find_routing_algorithm_by_algorithm_id_merchant_id(\n &algorithm_id,\n merchant_account.get_id(),\n )\n .await\n .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;\n\n let business_profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n Some(&routing_algorithm.profile_id),\n merchant_account.get_id(),\n )\n .await?\n .get_required_value(\"Profile\")\n .change_context(errors::ApiErrorResponse::ProfileNotFound {\n id: routing_algorithm.profile_id.get_string_repr().to_owned(),\n })?;\n\n core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;\n\n match routing_algorithm.kind {\n diesel_models::enums::RoutingAlgorithmKind::Dynamic => {\n let mut dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize Dynamic routing algorithm ref from business profile\",\n )?\n .unwrap_or_default();\n\n // Need to add contract based routing here\n utils::when(\n matches!(\n dynamic_routing_ref.success_based_algorithm,\n Some(routing::SuccessBasedAlgorithm {\n algorithm_id_with_timestamp:\n routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(ref id),\n timestamp: _\n },\n enabled_feature: _\n }) if id == &algorithm_id\n ) || matches!(\n dynamic_routing_ref.elimination_routing_algorithm,\n Some(routing::EliminationRoutingAlgorithm {\n algorithm_id_with_timestamp:\n routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(ref id),\n timestamp: _\n },\n enabled_feature: _\n }) if id == &algorithm_id\n ),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Algorithm is already active\".to_string(),\n })\n },\n )?;\n\n dynamic_routing_ref.update_algorithm_id(\n algorithm_id,\n dynamic_routing_ref\n .success_based_algorithm\n .clone()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"missing success_based_algorithm in dynamic_algorithm_ref from business_profile table\",\n )?\n .enabled_feature,\n routing_types::DynamicRoutingType::SuccessRateBasedRouting,\n );\n\n helpers::update_business_profile_active_dynamic_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n dynamic_routing_ref,\n )\n .await?;\n }\n diesel_models::enums::RoutingAlgorithmKind::Single\n | diesel_models::enums::RoutingAlgorithmKind::Priority\n | diesel_models::enums::RoutingAlgorithmKind::Advanced\n | diesel_models::enums::RoutingAlgorithmKind::VolumeSplit => {\n let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile\n .routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"RoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize routing algorithm ref from business profile\",\n )?\n .unwrap_or_default();\n\n utils::when(routing_algorithm.algorithm_for != *transaction_type, || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: format!(\n \"Cannot use {}'s routing algorithm for {} operation\",\n routing_algorithm.algorithm_for, transaction_type\n ),\n })\n })?;\n\n utils::when(\n routing_ref.algorithm_id == Some(algorithm_id.clone()),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Algorithm is already active\".to_string(),\n })\n },\n )?;\n routing_ref.update_algorithm_id(algorithm_id);\n helpers::update_profile_active_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n routing_ref,\n transaction_type,\n )\n .await?;\n }\n };\n\n metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);\n Ok(service_api::ApplicationResponse::Json(\n routing_algorithm.foreign_into(),\n ))\n}",
|
| 16 |
+
"after_code": "pub async fn link_routing_config(\n state: SessionState,\n merchant_account: domain::MerchantAccount,\n key_store: domain::MerchantKeyStore,\n authentication_profile_id: Option<common_utils::id_type::ProfileId>,\n algorithm_id: common_utils::id_type::RoutingId,\n transaction_type: &enums::TransactionType,\n) -> RouterResponse<routing_types::RoutingDictionaryRecord> {\n metrics::ROUTING_LINK_CONFIG.add(1, &[]);\n let db = state.store.as_ref();\n let key_manager_state = &(&state).into();\n\n let routing_algorithm = db\n .find_routing_algorithm_by_algorithm_id_merchant_id(\n &algorithm_id,\n merchant_account.get_id(),\n )\n .await\n .change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;\n\n let business_profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n Some(&routing_algorithm.profile_id),\n merchant_account.get_id(),\n )\n .await?\n .get_required_value(\"Profile\")\n .change_context(errors::ApiErrorResponse::ProfileNotFound {\n id: routing_algorithm.profile_id.get_string_repr().to_owned(),\n })?;\n\n core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;\n\n match routing_algorithm.kind {\n diesel_models::enums::RoutingAlgorithmKind::Dynamic => {\n let mut dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize Dynamic routing algorithm ref from business profile\",\n )?\n .unwrap_or_default();\n\n utils::when(\n matches!(\n dynamic_routing_ref.success_based_algorithm,\n Some(routing::SuccessBasedAlgorithm {\n algorithm_id_with_timestamp:\n routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(ref id),\n timestamp: _\n },\n enabled_feature: _\n }) if id == &algorithm_id\n ) || matches!(\n dynamic_routing_ref.elimination_routing_algorithm,\n Some(routing::EliminationRoutingAlgorithm {\n algorithm_id_with_timestamp:\n routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(ref id),\n timestamp: _\n },\n enabled_feature: _\n }) if id == &algorithm_id\n ) || matches!(\n dynamic_routing_ref.contract_based_routing,\n Some(routing::ContractRoutingAlgorithm {\n algorithm_id_with_timestamp:\n routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(ref id),\n timestamp: _\n },\n enabled_feature: _\n }) if id == &algorithm_id\n ),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Algorithm is already active\".to_string(),\n })\n },\n )?;\n\n println!(\"algo is - {:?}\", routing_algorithm.algorithm_data.clone());\n\n // These checks would be Expensive\n // A better way to do this would be to have some typed information in the algorithm_data\n if &routing_algorithm.name == helpers::SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM {\n dynamic_routing_ref.update_algorithm_id(\n algorithm_id,\n dynamic_routing_ref\n .success_based_algorithm\n .clone()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"missing success_based_algorithm in dynamic_algorithm_ref from business_profile table\",\n )?\n .enabled_feature,\n routing_types::DynamicRoutingType::SuccessRateBasedRouting,\n );\n } else if &routing_algorithm.name\n == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM\n {\n dynamic_routing_ref.update_algorithm_id(\n algorithm_id,\n dynamic_routing_ref\n .elimination_routing_algorithm\n .clone()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"missing elimination_routing_algorithm in dynamic_algorithm_ref from business_profile table\",\n )?\n .enabled_feature,\n routing_types::DynamicRoutingType::EliminationRouting,\n );\n } else if &routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM {\n dynamic_routing_ref.update_algorithm_id(\n algorithm_id,\n dynamic_routing_ref\n .contract_based_routing\n .clone()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"missing contract_based_routing in dynamic_algorithm_ref from business_profile table\",\n )?\n .enabled_feature,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n );\n }\n\n helpers::update_business_profile_active_dynamic_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n dynamic_routing_ref,\n )\n .await?;\n }\n diesel_models::enums::RoutingAlgorithmKind::Single\n | diesel_models::enums::RoutingAlgorithmKind::Priority\n | diesel_models::enums::RoutingAlgorithmKind::Advanced\n | diesel_models::enums::RoutingAlgorithmKind::VolumeSplit => {\n let mut routing_ref: routing_types::RoutingAlgorithmRef = business_profile\n .routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"RoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize routing algorithm ref from business profile\",\n )?\n .unwrap_or_default();\n\n utils::when(routing_algorithm.algorithm_for != *transaction_type, || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: format!(\n \"Cannot use {}'s routing algorithm for {} operation\",\n routing_algorithm.algorithm_for, transaction_type\n ),\n })\n })?;\n\n utils::when(\n routing_ref.algorithm_id == Some(algorithm_id.clone()),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Algorithm is already active\".to_string(),\n })\n },\n )?;\n routing_ref.update_algorithm_id(algorithm_id);\n helpers::update_profile_active_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n routing_ref,\n transaction_type,\n )\n .await?;\n }\n };\n\n metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);\n Ok(service_api::ApplicationResponse::Json(\n routing_algorithm.foreign_into(),\n ))\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " .unwrap_or_default();\n\n // Need to add contract based routing here\n utils::when(\n matches!(\n dynamic_routing_ref.success_based_algorithm,\n Some(routing::SuccessBasedAlgorithm {\n algorithm_id_with_timestamp:\n routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(ref id),\n timestamp: _\n },\n enabled_feature: _\n }) if id == &algorithm_id\n ) || matches!(\n dynamic_routing_ref.elimination_routing_algorithm,\n Some(routing::EliminationRoutingAlgorithm {\n algorithm_id_with_timestamp:\n routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(ref id),\n timestamp: _\n },\n enabled_feature: _\n }) if id == &algorithm_id\n ),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Algorithm is already active\".to_string(),\n })\n },\n )?;\n\n dynamic_routing_ref.update_algorithm_id(\n algorithm_id,\n dynamic_routing_ref",
|
| 19 |
+
"after": " enabled_feature: _\n }) if id == &algorithm_id\n ) || matches!(\n dynamic_routing_ref.contract_based_routing,\n Some(routing::ContractRoutingAlgorithm {\n algorithm_id_with_timestamp:\n routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(ref id),\n timestamp: _\n },\n enabled_feature: _\n }) if id == &algorithm_id\n ),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Algorithm is already active\".to_string(),\n })\n },\n )?;\n\n println!(\"algo is - {:?}\", routing_algorithm.algorithm_data.clone());\n\n // These checks would be Expensive\n // A better way to do this would be to have some typed information in the algorithm_data\n if &routing_algorithm.name == helpers::SUCCESS_BASED_DYNAMIC_ROUTING_ALGORITHM {\n dynamic_routing_ref.update_algorithm_id(\n algorithm_id,\n dynamic_routing_ref\n .success_based_algorithm\n .clone()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"missing success_based_algorithm in dynamic_algorithm_ref from business_profile table\",\n )?\n .enabled_feature,\n routing_types::DynamicRoutingType::SuccessRateBasedRouting,\n );\n } else if &routing_algorithm.name\n == helpers::ELIMINATION_BASED_DYNAMIC_ROUTING_ALGORITHM\n {\n dynamic_routing_ref.update_algorithm_id(\n algorithm_id,\n dynamic_routing_ref\n .elimination_routing_algorithm\n .clone()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"missing elimination_routing_algorithm in dynamic_algorithm_ref from business_profile table\",\n )?\n .enabled_feature,\n routing_types::DynamicRoutingType::EliminationRouting,\n );\n } else if &routing_algorithm.name == helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM {\n dynamic_routing_ref.update_algorithm_id(\n algorithm_id,\n dynamic_routing_ref\n .contract_based_routing\n .clone()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"missing contract_based_routing in dynamic_algorithm_ref from business_profile table\",\n )?\n .enabled_feature,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n );\n }\n\n helpers::update_business_profile_active_dynamic_algorithm_ref("
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "130ce8e1959868296156ecf9a013a4bdafb0553f"
|
| 22 |
+
}
|
| 23 |
+
]
|
| 24 |
+
}
|
diffs/pr_6761/1429f81/diff.json
ADDED
|
@@ -0,0 +1,169 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/api_models/src/routing.rs",
|
| 6 |
+
"crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs"
|
| 7 |
+
],
|
| 8 |
+
"diffs": [
|
| 9 |
+
{
|
| 10 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::ContractScoreCalculatorClient<Client>::function::update_contracts",
|
| 11 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 12 |
+
"kind": "function_item",
|
| 13 |
+
"status": "modified",
|
| 14 |
+
"code_changed": true,
|
| 15 |
+
"imports_changed": true,
|
| 16 |
+
"before_code": "async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let mut request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }",
|
| 17 |
+
"after_code": "async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let mut request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n logger::info!(dynamic_routing_response=?response);\n\n Ok(response)\n }",
|
| 18 |
+
"diff_span": {
|
| 19 |
+
"before": "",
|
| 20 |
+
"after": " .into_inner();\n\n logger::info!(dynamic_routing_response=?response);\n\n Ok(response)\n }"
|
| 21 |
+
},
|
| 22 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b",
|
| 23 |
+
"before_imports": [
|
| 24 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 25 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 26 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 27 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 28 |
+
],
|
| 29 |
+
"after_imports": [
|
| 30 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 31 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};",
|
| 32 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 33 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 34 |
+
"use router_env::logger;"
|
| 35 |
+
]
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::impl::ContractScoreCalculatorClient<Client>",
|
| 39 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 40 |
+
"kind": "impl_item",
|
| 41 |
+
"status": "modified",
|
| 42 |
+
"code_changed": true,
|
| 43 |
+
"imports_changed": true,
|
| 44 |
+
"before_code": "impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> {\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let mut request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let mut request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n async fn invalidate_contracts(\n &self,\n id: String,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let mut request = tonic::Request::new(InvalidateContractRequest { id });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .invalidate_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to invalidate the contracts\".to_string(),\n ))?\n .into_inner();\n Ok(response)\n }\n}",
|
| 45 |
+
"after_code": "impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> {\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let mut request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n logger::info!(dynamic_routing_response=?response);\n\n Ok(response)\n }\n\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let mut request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n logger::info!(dynamic_routing_response=?response);\n\n Ok(response)\n }\n async fn invalidate_contracts(\n &self,\n id: String,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let mut request = tonic::Request::new(InvalidateContractRequest { id });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .invalidate_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to invalidate the contracts\".to_string(),\n ))?\n .into_inner();\n Ok(response)\n }\n}",
|
| 46 |
+
"diff_span": {
|
| 47 |
+
"before": "",
|
| 48 |
+
"after": " .into_inner();\n\n logger::info!(dynamic_routing_response=?response);\n\n Ok(response)\n }\n\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let mut request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n logger::info!(dynamic_routing_response=?response);\n\n Ok(response)\n }"
|
| 49 |
+
},
|
| 50 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b",
|
| 51 |
+
"before_imports": [
|
| 52 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 53 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 54 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 55 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 56 |
+
],
|
| 57 |
+
"after_imports": [
|
| 58 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 59 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};",
|
| 60 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 61 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 62 |
+
"use router_env::logger;"
|
| 63 |
+
]
|
| 64 |
+
},
|
| 65 |
+
{
|
| 66 |
+
"id": "crates/api_models/src/routing.rs::impl::ContractBasedRoutingConfig",
|
| 67 |
+
"file": "crates/api_models/src/routing.rs",
|
| 68 |
+
"kind": "impl_item",
|
| 69 |
+
"status": "modified",
|
| 70 |
+
"code_changed": true,
|
| 71 |
+
"imports_changed": false,
|
| 72 |
+
"before_code": "impl ContractBasedRoutingConfig {\n pub fn update(&mut self, new: Self) {\n if let Some(new_config) = new.config {\n self.config.as_mut().map(|config| config.update(new_config));\n }\n if let Some(new_label_info) = new.label_info {\n new_label_info.iter().for_each(|new_label_info| {\n if let Some(existing_label_infos) = &mut self.label_info {\n for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info\n .update_target_time_and_count(new_label_info.clone());\n }\n }\n } else {\n self.label_info = Some(vec![new_label_info.clone()]);\n }\n });\n }\n }\n}",
|
| 73 |
+
"after_code": "impl ContractBasedRoutingConfig {\n pub fn update(&mut self, new: Self) {\n if let Some(new_config) = new.config {\n self.config.as_mut().map(|config| config.update(new_config));\n }\n if let Some(new_label_info) = new.label_info {\n new_label_info.iter().for_each(|new_label_info| {\n if let Some(existing_label_infos) = &mut self.label_info {\n for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(&new_label_info);\n existing_label_info.update_target_count(&new_label_info);\n }\n }\n } else {\n self.label_info = Some(vec![new_label_info.clone()]);\n }\n });\n }\n }\n}",
|
| 74 |
+
"diff_span": {
|
| 75 |
+
"before": " for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info\n .update_target_time_and_count(new_label_info.clone());\n }\n }",
|
| 76 |
+
"after": " for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(&new_label_info);\n existing_label_info.update_target_count(&new_label_info);\n }\n }"
|
| 77 |
+
},
|
| 78 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b"
|
| 79 |
+
},
|
| 80 |
+
{
|
| 81 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::ContractScoreCalculatorClient<Client>::function::calculate_contract_score",
|
| 82 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 83 |
+
"kind": "function_item",
|
| 84 |
+
"status": "modified",
|
| 85 |
+
"code_changed": true,
|
| 86 |
+
"imports_changed": true,
|
| 87 |
+
"before_code": "async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let mut request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }",
|
| 88 |
+
"after_code": "async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let mut request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n logger::info!(dynamic_routing_response=?response);\n\n Ok(response)\n }",
|
| 89 |
+
"diff_span": {
|
| 90 |
+
"before": "",
|
| 91 |
+
"after": " .into_inner();\n\n logger::info!(dynamic_routing_response=?response);\n\n Ok(response)\n }"
|
| 92 |
+
},
|
| 93 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b",
|
| 94 |
+
"before_imports": [
|
| 95 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 96 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 97 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 98 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 99 |
+
],
|
| 100 |
+
"after_imports": [
|
| 101 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 102 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};",
|
| 103 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 104 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 105 |
+
"use router_env::logger;"
|
| 106 |
+
]
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"id": "crates/api_models/src/routing.rs::ContractBasedRoutingConfig::function::update",
|
| 110 |
+
"file": "crates/api_models/src/routing.rs",
|
| 111 |
+
"kind": "function_item",
|
| 112 |
+
"status": "modified",
|
| 113 |
+
"code_changed": true,
|
| 114 |
+
"imports_changed": false,
|
| 115 |
+
"before_code": "pub fn update(&mut self, new: Self) {\n if let Some(new_config) = new.config {\n self.config.as_mut().map(|config| config.update(new_config));\n }\n if let Some(new_label_info) = new.label_info {\n new_label_info.iter().for_each(|new_label_info| {\n if let Some(existing_label_infos) = &mut self.label_info {\n for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info\n .update_target_time_and_count(new_label_info.clone());\n }\n }\n } else {\n self.label_info = Some(vec![new_label_info.clone()]);\n }\n });\n }\n }",
|
| 116 |
+
"after_code": "pub fn update(&mut self, new: Self) {\n if let Some(new_config) = new.config {\n self.config.as_mut().map(|config| config.update(new_config));\n }\n if let Some(new_label_info) = new.label_info {\n new_label_info.iter().for_each(|new_label_info| {\n if let Some(existing_label_infos) = &mut self.label_info {\n for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(&new_label_info);\n existing_label_info.update_target_count(&new_label_info);\n }\n }\n } else {\n self.label_info = Some(vec![new_label_info.clone()]);\n }\n });\n }\n }",
|
| 117 |
+
"diff_span": {
|
| 118 |
+
"before": " for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info\n .update_target_time_and_count(new_label_info.clone());\n }\n }",
|
| 119 |
+
"after": " for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(&new_label_info);\n existing_label_info.update_target_count(&new_label_info);\n }\n }"
|
| 120 |
+
},
|
| 121 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b"
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"id": "crates/api_models/src/routing.rs::impl::LabelInformation",
|
| 125 |
+
"file": "crates/api_models/src/routing.rs",
|
| 126 |
+
"kind": "impl_item",
|
| 127 |
+
"status": "modified",
|
| 128 |
+
"code_changed": true,
|
| 129 |
+
"imports_changed": false,
|
| 130 |
+
"before_code": "impl LabelInformation {\n pub fn update_target_time_and_count(&mut self, new: Self) {\n self.target_count = new.target_count;\n self.target_time = new.target_time;\n }\n}",
|
| 131 |
+
"after_code": "impl LabelInformation {\n pub fn update_target_time(&mut self, new: &Self) {\n self.target_time = new.target_time;\n }\n\n pub fn update_target_count(&mut self, new: &Self) {\n self.target_count = new.target_count;\n }\n}",
|
| 132 |
+
"diff_span": {
|
| 133 |
+
"before": "impl LabelInformation {\n pub fn update_target_time_and_count(&mut self, new: Self) {\n self.target_count = new.target_count;\n self.target_time = new.target_time;\n }",
|
| 134 |
+
"after": "impl LabelInformation {\n pub fn update_target_time(&mut self, new: &Self) {\n self.target_time = new.target_time;\n }\n\n pub fn update_target_count(&mut self, new: &Self) {\n self.target_count = new.target_count;\n }\n}"
|
| 135 |
+
},
|
| 136 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b"
|
| 137 |
+
},
|
| 138 |
+
{
|
| 139 |
+
"id": "crates/api_models/src/routing.rs::LabelInformation::function::update_target_time",
|
| 140 |
+
"file": "crates/api_models/src/routing.rs",
|
| 141 |
+
"kind": "function_item",
|
| 142 |
+
"status": "added",
|
| 143 |
+
"before_code": null,
|
| 144 |
+
"after_code": "pub fn update_target_time(&mut self, new: &Self) {\n self.target_time = new.target_time;\n }",
|
| 145 |
+
"diff_span": null,
|
| 146 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b"
|
| 147 |
+
},
|
| 148 |
+
{
|
| 149 |
+
"id": "crates/api_models/src/routing.rs::LabelInformation::function::update_target_count",
|
| 150 |
+
"file": "crates/api_models/src/routing.rs",
|
| 151 |
+
"kind": "function_item",
|
| 152 |
+
"status": "added",
|
| 153 |
+
"before_code": null,
|
| 154 |
+
"after_code": "pub fn update_target_count(&mut self, new: &Self) {\n self.target_count = new.target_count;\n }",
|
| 155 |
+
"diff_span": null,
|
| 156 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b"
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"id": "crates/api_models/src/routing.rs::LabelInformation::function::update_target_time_and_count",
|
| 160 |
+
"file": "crates/api_models/src/routing.rs",
|
| 161 |
+
"kind": "function_item",
|
| 162 |
+
"status": "removed",
|
| 163 |
+
"before_code": "pub fn update_target_time_and_count(&mut self, new: Self) {\n self.target_count = new.target_count;\n self.target_time = new.target_time;\n }",
|
| 164 |
+
"after_code": null,
|
| 165 |
+
"diff_span": null,
|
| 166 |
+
"commit_sha": "1429f814339f36c0331968a1aec058218f884f7b"
|
| 167 |
+
}
|
| 168 |
+
]
|
| 169 |
+
}
|
diffs/pr_6761/17044b1/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_6761/17648f3/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_6761/198a308/diff.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "198a308f731ac1eb6f0d7b88119a7b99310f1bcc",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs::CalContractScoreConfig::function::foreign_try_from",
|
| 10 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs",
|
| 11 |
+
"kind": "function_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config\n .time_scale\n .clone()\n .map(TimeScale::foreign_from),\n })\n }",
|
| 16 |
+
"after_code": "fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config.time_scale.clone().map(TimeScale::foreign_from),\n })\n }",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " field: \"constants\".to_string(),\n })?,\n time_scale: config\n .time_scale\n .clone()\n .map(TimeScale::foreign_from),\n })\n }",
|
| 19 |
+
"after": " field: \"constants\".to_string(),\n })?,\n time_scale: config.time_scale.clone().map(TimeScale::foreign_from),\n })\n }"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "198a308f731ac1eb6f0d7b88119a7b99310f1bcc"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs::impl::CalContractScoreConfig",
|
| 25 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs",
|
| 26 |
+
"kind": "impl_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig {\n type Error = error_stack::Report<DynamicRoutingError>;\n fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config\n .time_scale\n .clone()\n .map(TimeScale::foreign_from),\n })\n }\n}",
|
| 31 |
+
"after_code": "impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig {\n type Error = error_stack::Report<DynamicRoutingError>;\n fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config.time_scale.clone().map(TimeScale::foreign_from),\n })\n }\n}",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " field: \"constants\".to_string(),\n })?,\n time_scale: config\n .time_scale\n .clone()\n .map(TimeScale::foreign_from),\n })\n }",
|
| 34 |
+
"after": " field: \"constants\".to_string(),\n })?,\n time_scale: config.time_scale.clone().map(TimeScale::foreign_from),\n })\n }"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "198a308f731ac1eb6f0d7b88119a7b99310f1bcc"
|
| 37 |
+
}
|
| 38 |
+
]
|
| 39 |
+
}
|
diffs/pr_6761/26f7a10/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_6761/354314a/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_6761/3c471f9/diff.json
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "3c471f9bf675bb162edc80cd9f13a5d3a03f3133",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/core/metrics.rs",
|
| 6 |
+
"crates/router/src/core/routing/helpers.rs"
|
| 7 |
+
],
|
| 8 |
+
"diffs": [
|
| 9 |
+
{
|
| 10 |
+
"id": "crates/router/src/core/routing/helpers.rs::function::push_metrics_with_update_window_for_contract_based_routing",
|
| 11 |
+
"file": "crates/router/src/core/routing/helpers.rs",
|
| 12 |
+
"kind": "function_item",
|
| 13 |
+
"status": "modified",
|
| 14 |
+
"code_changed": true,
|
| 15 |
+
"imports_changed": false,
|
| 16 |
+
"before_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ]),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 17 |
+
"after_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ]),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 18 |
+
"diff_span": {
|
| 19 |
+
"before": " .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,",
|
| 20 |
+
"after": " .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,"
|
| 21 |
+
},
|
| 22 |
+
"commit_sha": "3c471f9bf675bb162edc80cd9f13a5d3a03f3133"
|
| 23 |
+
}
|
| 24 |
+
]
|
| 25 |
+
}
|
diffs/pr_6761/405eaa5/diff.json
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "405eaa55f3f3ebf869b397ab3255080a91e7f7fe",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/router/src/core/routing.rs",
|
| 6 |
+
"crates/router/src/core/routing/helpers.rs"
|
| 7 |
+
],
|
| 8 |
+
"diffs": [
|
| 9 |
+
{
|
| 10 |
+
"id": "crates/router/src/core/routing/helpers.rs::function::push_metrics_with_update_window_for_contract_based_routing",
|
| 11 |
+
"file": "crates/router/src/core/routing/helpers.rs",
|
| 12 |
+
"kind": "function_item",
|
| 13 |
+
"status": "modified",
|
| 14 |
+
"code_changed": true,
|
| 15 |
+
"imports_changed": false,
|
| 16 |
+
"before_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n profile_id: &id_type::ProfileId,\n dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,\n _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n profile_id,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"contract_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve contract based dynamic routing configs\")?;\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\n \"contract based routing: matched LabelInformation - {:?}\",\n final_label_info\n );\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n let payment_status_attribute =\n get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);\n\n if payment_status_attribute == common_enums::AttemptStatus::Charged {\n client\n .update_contracts(\n profile_id.get_string_repr().into(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n state.get_grpc_headers(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update contract based routing window in dynamic routing service\",\n )?;\n }\n\n let contract_scores = client\n .calculate_contract_score(\n profile_id.get_string_repr().into(),\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n state.get_grpc_headers(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n 1,\n router_env::metric_attributes!(\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n ),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 17 |
+
"after_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n profile_id: &id_type::ProfileId,\n dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef,\n _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n profile_id,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"contract_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve contract based dynamic routing configs\")?;\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\n \"contract based routing: matched LabelInformation - {:?}\",\n final_label_info\n );\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n let payment_status_attribute =\n get_desired_payment_status_for_dynamic_routing_metrics(payment_attempt.status);\n\n if payment_status_attribute == common_enums::AttemptStatus::Charged {\n client\n .update_contracts(\n profile_id.get_string_repr().into(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n state.get_grpc_headers(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update contract based routing window in dynamic routing service\",\n )?;\n }\n\n let contract_scores = client\n .calculate_contract_score(\n profile_id.get_string_repr().into(),\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n state.get_grpc_headers(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n 1,\n router_env::metric_attributes!(\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n ),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 18 |
+
"diff_span": {
|
| 19 |
+
"before": "",
|
| 20 |
+
"after": " ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n ),\n );"
|
| 21 |
+
},
|
| 22 |
+
"commit_sha": "405eaa55f3f3ebf869b397ab3255080a91e7f7fe"
|
| 23 |
+
},
|
| 24 |
+
{
|
| 25 |
+
"id": "crates/router/src/core/routing.rs::function::contract_based_dynamic_routing_setup",
|
| 26 |
+
"file": "crates/router/src/core/routing.rs",
|
| 27 |
+
"kind": "function_item",
|
| 28 |
+
"status": "modified",
|
| 29 |
+
"code_changed": true,
|
| 30 |
+
"imports_changed": false,
|
| 31 |
+
"before_code": "pub async fn contract_based_dynamic_routing_setup(\n state: SessionState,\n key_store: domain::MerchantKeyStore,\n merchant_account: domain::MerchantAccount,\n profile_id: common_utils::id_type::ProfileId,\n feature_to_enable: routing_types::DynamicRoutingFeatures,\n config: Option<routing_types::ContractBasedRoutingConfig>,\n) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> {\n let db = state.store.as_ref();\n let key_manager_state = &(&state).into();\n\n let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n Some(&profile_id),\n merchant_account.get_id(),\n )\n .await?\n .get_required_value(\"Profile\")\n .change_context(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize dynamic routing algorithm ref from business profile\",\n )\n .ok()\n .flatten();\n\n utils::when(\n dynamic_routing_algo_ref\n .as_mut()\n .and_then(|algo| {\n algo.contract_based_routing.as_mut().map(|contract_algo| {\n *contract_algo.get_enabled_features() == feature_to_enable\n && contract_algo\n .clone()\n .get_algorithm_id_with_timestamp()\n .algorithm_id\n .is_some()\n })\n })\n .unwrap_or(false),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Contract Routing with specified features is already enabled\".to_string(),\n })\n },\n )?;\n\n if feature_to_enable == routing::DynamicRoutingFeatures::None {\n let algorithm = dynamic_routing_algo_ref\n .clone()\n .get_required_value(\"dynamic_routing_algo_ref\")\n .attach_printable(\"Failed to get dynamic_routing_algo_ref\")?;\n return helpers::disable_dynamic_routing_algorithm(\n &state,\n key_store,\n business_profile,\n algorithm,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n )\n .await;\n }\n\n let config = config\n .get_required_value(\"ContractBasedRoutingConfig\")\n .attach_printable(\"Failed to get ContractBasedRoutingConfig from request\")?;\n\n let merchant_id = business_profile.merchant_id.clone();\n let algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n\n let algo = RoutingAlgorithm {\n algorithm_id: algorithm_id.clone(),\n profile_id: profile_id.clone(),\n merchant_id,\n name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),\n description: None,\n kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,\n algorithm_data: serde_json::json!(config),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: common_enums::TransactionType::Payment,\n };\n\n // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based\n // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up\n let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref {\n algo.update_algorithm_id(\n algorithm_id,\n feature_to_enable,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n );\n if feature_to_enable == routing::DynamicRoutingFeatures::DynamicConnectorSelection {\n algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting);\n }\n algo\n } else {\n let contract_algo = routing_types::ContractRoutingAlgorithm {\n algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp::new(Some(\n algorithm_id.clone(),\n )),\n enabled_feature: feature_to_enable,\n };\n routing_types::DynamicRoutingAlgorithmRef {\n success_based_algorithm: None,\n elimination_routing_algorithm: None,\n dynamic_routing_volume_split: None,\n contract_based_routing: Some(contract_algo),\n }\n };\n\n // validate the contained mca_ids\n if let Some(info_vec) = &config.label_info {\n let validation_futures: Vec<_> = info_vec\n .iter()\n .map(|info| async {\n let mca_id = info.mca_id.clone();\n let label = info.label.clone();\n let mca = db\n .find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n key_manager_state,\n merchant_account.get_id(),\n &mca_id,\n &key_store,\n )\n .await\n .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: mca_id.get_string_repr().to_owned(),\n })?;\n\n utils::when(mca.connector_name != label, || {\n Err(error_stack::Report::new(\n errors::ApiErrorResponse::InvalidRequestData {\n message: \"Incorrect mca configuration received\".to_string(),\n },\n ))\n })?;\n\n Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(())\n })\n .collect();\n\n futures::future::try_join_all(validation_futures).await?;\n }\n\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n helpers::update_business_profile_active_dynamic_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n final_algorithm,\n )\n .await?;\n\n // Should we also update at dynamic routing service?\n let new_record = record.foreign_into();\n\n metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_string())),\n );\n Ok(service_api::ApplicationResponse::Json(new_record))\n}",
|
| 32 |
+
"after_code": "pub async fn contract_based_dynamic_routing_setup(\n state: SessionState,\n key_store: domain::MerchantKeyStore,\n merchant_account: domain::MerchantAccount,\n profile_id: common_utils::id_type::ProfileId,\n feature_to_enable: routing_types::DynamicRoutingFeatures,\n config: Option<routing_types::ContractBasedRoutingConfig>,\n) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> {\n let db = state.store.as_ref();\n let key_manager_state = &(&state).into();\n\n let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n Some(&profile_id),\n merchant_account.get_id(),\n )\n .await?\n .get_required_value(\"Profile\")\n .change_context(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize dynamic routing algorithm ref from business profile\",\n )\n .ok()\n .flatten();\n\n utils::when(\n dynamic_routing_algo_ref\n .as_mut()\n .and_then(|algo| {\n algo.contract_based_routing.as_mut().map(|contract_algo| {\n *contract_algo.get_enabled_features() == feature_to_enable\n && contract_algo\n .clone()\n .get_algorithm_id_with_timestamp()\n .algorithm_id\n .is_some()\n })\n })\n .unwrap_or(false),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Contract Routing with specified features is already enabled\".to_string(),\n })\n },\n )?;\n\n if feature_to_enable == routing::DynamicRoutingFeatures::None {\n let algorithm = dynamic_routing_algo_ref\n .clone()\n .get_required_value(\"dynamic_routing_algo_ref\")\n .attach_printable(\"Failed to get dynamic_routing_algo_ref\")?;\n return helpers::disable_dynamic_routing_algorithm(\n &state,\n key_store,\n business_profile,\n algorithm,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n )\n .await;\n }\n\n let config = config\n .get_required_value(\"ContractBasedRoutingConfig\")\n .attach_printable(\"Failed to get ContractBasedRoutingConfig from request\")?;\n\n let merchant_id = business_profile.merchant_id.clone();\n let algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n\n let algo = RoutingAlgorithm {\n algorithm_id: algorithm_id.clone(),\n profile_id: profile_id.clone(),\n merchant_id,\n name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),\n description: None,\n kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,\n algorithm_data: serde_json::json!(config),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: common_enums::TransactionType::Payment,\n };\n\n // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based\n // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up\n let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref {\n algo.update_algorithm_id(\n algorithm_id,\n feature_to_enable,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n );\n if feature_to_enable == routing::DynamicRoutingFeatures::DynamicConnectorSelection {\n algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting);\n }\n algo\n } else {\n let contract_algo = routing_types::ContractRoutingAlgorithm {\n algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp::new(Some(\n algorithm_id.clone(),\n )),\n enabled_feature: feature_to_enable,\n };\n routing_types::DynamicRoutingAlgorithmRef {\n success_based_algorithm: None,\n elimination_routing_algorithm: None,\n dynamic_routing_volume_split: None,\n contract_based_routing: Some(contract_algo),\n }\n };\n\n // validate the contained mca_ids\n if let Some(info_vec) = &config.label_info {\n let validation_futures: Vec<_> = info_vec\n .iter()\n .map(|info| async {\n let mca_id = info.mca_id.clone();\n let label = info.label.clone();\n let mca = db\n .find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n key_manager_state,\n merchant_account.get_id(),\n &mca_id,\n &key_store,\n )\n .await\n .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: mca_id.get_string_repr().to_owned(),\n })?;\n\n utils::when(mca.connector_name != label, || {\n Err(error_stack::Report::new(\n errors::ApiErrorResponse::InvalidRequestData {\n message: \"Incorrect mca configuration received\".to_string(),\n },\n ))\n })?;\n\n Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(())\n })\n .collect();\n\n futures::future::try_join_all(validation_futures).await?;\n }\n\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n helpers::update_business_profile_active_dynamic_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n final_algorithm,\n )\n .await?;\n\n let new_record = record.foreign_into();\n\n metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_string())),\n );\n Ok(service_api::ApplicationResponse::Json(new_record))\n}",
|
| 33 |
+
"diff_span": {
|
| 34 |
+
"before": " .await?;\n\n // Should we also update at dynamic routing service?\n let new_record = record.foreign_into();\n",
|
| 35 |
+
"after": ""
|
| 36 |
+
},
|
| 37 |
+
"commit_sha": "405eaa55f3f3ebf869b397ab3255080a91e7f7fe"
|
| 38 |
+
}
|
| 39 |
+
]
|
| 40 |
+
}
|
diffs/pr_6761/4f12340/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
diffs/pr_6761/535532c/diff.json
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "535532c2fea697cbc0cc3a823d849a3aaf093f39",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/external_services/src/grpc_client/dynamic_routing.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": []
|
| 8 |
+
}
|
diffs/pr_6761/55dc858/diff.json
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "55dc858a2054e4b7b19f1503fad9e132a88545d6",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/api_models/src/routing.rs"
|
| 6 |
+
],
|
| 7 |
+
"diffs": [
|
| 8 |
+
{
|
| 9 |
+
"id": "crates/api_models/src/routing.rs::impl::ContractBasedRoutingConfig",
|
| 10 |
+
"file": "crates/api_models/src/routing.rs",
|
| 11 |
+
"kind": "impl_item",
|
| 12 |
+
"status": "modified",
|
| 13 |
+
"code_changed": true,
|
| 14 |
+
"imports_changed": false,
|
| 15 |
+
"before_code": "impl ContractBasedRoutingConfig {\n pub fn update(&mut self, new: Self) {\n if let Some(new_config) = new.config {\n self.config.as_mut().map(|config| config.update(new_config));\n }\n if let Some(new_label_info) = new.label_info {\n new_label_info.iter().for_each(|new_label_info| {\n if let Some(existing_label_infos) = &mut self.label_info {\n for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(&new_label_info);\n existing_label_info.update_target_count(&new_label_info);\n }\n }\n } else {\n self.label_info = Some(vec![new_label_info.clone()]);\n }\n });\n }\n }\n}",
|
| 16 |
+
"after_code": "impl ContractBasedRoutingConfig {\n pub fn update(&mut self, new: Self) {\n if let Some(new_config) = new.config {\n self.config.as_mut().map(|config| config.update(new_config));\n }\n if let Some(new_label_info) = new.label_info {\n new_label_info.iter().for_each(|new_label_info| {\n if let Some(existing_label_infos) = &mut self.label_info {\n for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(new_label_info);\n existing_label_info.update_target_count(new_label_info);\n }\n }\n } else {\n self.label_info = Some(vec![new_label_info.clone()]);\n }\n });\n }\n }\n}",
|
| 17 |
+
"diff_span": {
|
| 18 |
+
"before": " for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(&new_label_info);\n existing_label_info.update_target_count(&new_label_info);\n }\n }",
|
| 19 |
+
"after": " for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(new_label_info);\n existing_label_info.update_target_count(new_label_info);\n }\n }"
|
| 20 |
+
},
|
| 21 |
+
"commit_sha": "55dc858a2054e4b7b19f1503fad9e132a88545d6"
|
| 22 |
+
},
|
| 23 |
+
{
|
| 24 |
+
"id": "crates/api_models/src/routing.rs::ContractBasedRoutingConfig::function::update",
|
| 25 |
+
"file": "crates/api_models/src/routing.rs",
|
| 26 |
+
"kind": "function_item",
|
| 27 |
+
"status": "modified",
|
| 28 |
+
"code_changed": true,
|
| 29 |
+
"imports_changed": false,
|
| 30 |
+
"before_code": "pub fn update(&mut self, new: Self) {\n if let Some(new_config) = new.config {\n self.config.as_mut().map(|config| config.update(new_config));\n }\n if let Some(new_label_info) = new.label_info {\n new_label_info.iter().for_each(|new_label_info| {\n if let Some(existing_label_infos) = &mut self.label_info {\n for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(&new_label_info);\n existing_label_info.update_target_count(&new_label_info);\n }\n }\n } else {\n self.label_info = Some(vec![new_label_info.clone()]);\n }\n });\n }\n }",
|
| 31 |
+
"after_code": "pub fn update(&mut self, new: Self) {\n if let Some(new_config) = new.config {\n self.config.as_mut().map(|config| config.update(new_config));\n }\n if let Some(new_label_info) = new.label_info {\n new_label_info.iter().for_each(|new_label_info| {\n if let Some(existing_label_infos) = &mut self.label_info {\n for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(new_label_info);\n existing_label_info.update_target_count(new_label_info);\n }\n }\n } else {\n self.label_info = Some(vec![new_label_info.clone()]);\n }\n });\n }\n }",
|
| 32 |
+
"diff_span": {
|
| 33 |
+
"before": " for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(&new_label_info);\n existing_label_info.update_target_count(&new_label_info);\n }\n }",
|
| 34 |
+
"after": " for existing_label_info in existing_label_infos {\n if existing_label_info.mca_id == new_label_info.mca_id {\n existing_label_info.update_target_time(new_label_info);\n existing_label_info.update_target_count(new_label_info);\n }\n }"
|
| 35 |
+
},
|
| 36 |
+
"commit_sha": "55dc858a2054e4b7b19f1503fad9e132a88545d6"
|
| 37 |
+
}
|
| 38 |
+
]
|
| 39 |
+
}
|
diffs/pr_6761/584db45/diff.json
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "584db459eed99bb47fe3ef79f0c23287c8701a15",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 6 |
+
"crates/router/src/core/routing.rs",
|
| 7 |
+
"crates/router/src/core/routing/helpers.rs"
|
| 8 |
+
],
|
| 9 |
+
"diffs": [
|
| 10 |
+
{
|
| 11 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing.rs::impl::DynamicRoutingClientConfig",
|
| 12 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 13 |
+
"kind": "impl_item",
|
| 14 |
+
"status": "modified",
|
| 15 |
+
"code_changed": true,
|
| 16 |
+
"imports_changed": false,
|
| 17 |
+
"before_code": "impl DynamicRoutingClientConfig {\n /// establish connection with the server\n pub async fn get_dynamic_routing_connection(\n self,\n client: Client,\n ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {\n let (success_rate_client, contract_based_client, elimination_based_client) = match self {\n Self::Enabled { host, port, .. } => {\n let uri = format!(\"http://{}:{}\", host, port).parse::<tonic::transport::Uri>()?;\n logger::info!(\"Connection established with dynamic routing gRPC Server\");\n (\n Some(SuccessRateCalculatorClient::with_origin(\n client.clone(),\n uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client, uri)),\n Some(EliminationAnalyserClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n elimination_rate_client,\n })\n }\n}",
|
| 18 |
+
"after_code": "impl DynamicRoutingClientConfig {\n /// establish connection with the server\n pub async fn get_dynamic_routing_connection(\n self,\n client: Client,\n ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {\n let (success_rate_client, contract_based_client, elimination_based_client) = match self {\n Self::Enabled { host, port, .. } => {\n let uri = format!(\"http://{}:{}\", host, port).parse::<tonic::transport::Uri>()?;\n logger::info!(\"Connection established with dynamic routing gRPC Server\");\n (\n Some(SuccessRateCalculatorClient::with_origin(\n client.clone(),\n uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client.clone(), uri.clone())),\n Some(EliminationAnalyserClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n elimination_rate_client: elimination_based_client,\n })\n }\n}",
|
| 19 |
+
"diff_span": {
|
| 20 |
+
"before": " uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client, uri)),\n Some(EliminationAnalyserClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n elimination_rate_client,\n })\n }",
|
| 21 |
+
"after": " uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client.clone(), uri.clone())),\n Some(EliminationAnalyserClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n elimination_rate_client: elimination_based_client,\n })\n }"
|
| 22 |
+
},
|
| 23 |
+
"commit_sha": "584db459eed99bb47fe3ef79f0c23287c8701a15"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"id": "crates/router/src/core/routing/helpers.rs::function::push_metrics_with_update_window_for_contract_based_routing",
|
| 27 |
+
"file": "crates/router/src/core/routing/helpers.rs",
|
| 28 |
+
"kind": "function_item",
|
| 29 |
+
"status": "modified",
|
| 30 |
+
"code_changed": true,
|
| 31 |
+
"imports_changed": false,
|
| 32 |
+
"before_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n // let payment_status_attribute =\n // get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ]),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 33 |
+
"after_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n if payment_status_attribute == common_enums::AttemptStatus::Charged {\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n }\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n 1,\n router_env::metric_attributes!(\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ));\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 34 |
+
"diff_span": {
|
| 35 |
+
"before": " };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n // let payment_status_attribute =\n // get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ]),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n",
|
| 36 |
+
"after": " };\n\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n if payment_status_attribute == common_enums::AttemptStatus::Charged {\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n }\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n 1,\n router_env::metric_attributes!(\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ));\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n"
|
| 37 |
+
},
|
| 38 |
+
"commit_sha": "584db459eed99bb47fe3ef79f0c23287c8701a15"
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"id": "crates/router/src/core/routing.rs::function::contract_based_routing_update_configs",
|
| 42 |
+
"file": "crates/router/src/core/routing.rs",
|
| 43 |
+
"kind": "function_item",
|
| 44 |
+
"status": "modified",
|
| 45 |
+
"code_changed": true,
|
| 46 |
+
"imports_changed": false,
|
| 47 |
+
"before_code": "pub async fn contract_based_routing_update_configs(\n state: SessionState,\n request: routing_types::ContractBasedRoutingConfig,\n algorithm_id: common_utils::id_type::RoutingId,\n profile_id: common_utils::id_type::ProfileId,\n) -> RouterResponse<routing_types::RoutingDictionaryRecord> {\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([(\"profile_id\", profile_id.get_string_repr().to_owned())]),\n );\n let db = state.store.as_ref();\n\n let dynamic_routing_algo_to_update = db\n .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)\n .await\n .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;\n\n let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update\n .algorithm_data\n .parse_value::<routing::ContractBasedRoutingConfig>(\"ContractBasedRoutingConfig\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig\")?;\n\n config_to_update.update(request);\n\n let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n let algo = RoutingAlgorithm {\n algorithm_id: updated_algorithm_id,\n profile_id: dynamic_routing_algo_to_update.profile_id,\n merchant_id: dynamic_routing_algo_to_update.merchant_id,\n name: dynamic_routing_algo_to_update.name,\n description: dynamic_routing_algo_to_update.description,\n kind: dynamic_routing_algo_to_update.kind,\n algorithm_data: serde_json::json!(config_to_update),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: dynamic_routing_algo_to_update.algorithm_for,\n };\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // redact cache for contract based routing configs\n let cache_key = format!(\n \"{}_{}\",\n profile_id.get_string_repr(),\n algorithm_id.get_string_repr()\n );\n let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache(\n cache_key.into(),\n )];\n let _ = cache::publish_into_redact_channel(\n state.store.get_cache_store().as_ref(),\n cache_entries_to_redact,\n )\n .await\n .map_err(|e| logger::error!(\"unable to publish into the redact channel for evicting the contract based routing config cache {e:?}\"));\n\n let new_record = record.foreign_into();\n\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([(\"profile_id\", profile_id.get_string_repr().to_owned())]),\n );\n\n let prefix_of_dynamic_routing_keys = helpers::generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n profile_id.get_string_repr(),\n );\n state\n .grpc_client\n .clone()\n .dynamic_routing\n .contract_based_client\n .clone()\n .async_map(|ct_client| async move {\n ct_client\n .invalidate_contracts(prefix_of_dynamic_routing_keys)\n .await\n .change_context(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"Failed to invalidate the routing keys\".to_string(),\n })\n })\n .await\n .transpose()?;\n\n Ok(service_api::ApplicationResponse::Json(new_record))\n}",
|
| 48 |
+
"after_code": "pub async fn contract_based_routing_update_configs(\n state: SessionState,\n request: routing_types::ContractBasedRoutingConfig,\n algorithm_id: common_utils::id_type::RoutingId,\n profile_id: common_utils::id_type::ProfileId,\n) -> RouterResponse<routing_types::RoutingDictionaryRecord> {\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_owned())),\n );\n let db = state.store.as_ref();\n\n let dynamic_routing_algo_to_update = db\n .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)\n .await\n .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;\n\n let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update\n .algorithm_data\n .parse_value::<routing::ContractBasedRoutingConfig>(\"ContractBasedRoutingConfig\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig\")?;\n\n config_to_update.update(request);\n\n let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n let algo = RoutingAlgorithm {\n algorithm_id: updated_algorithm_id,\n profile_id: dynamic_routing_algo_to_update.profile_id,\n merchant_id: dynamic_routing_algo_to_update.merchant_id,\n name: dynamic_routing_algo_to_update.name,\n description: dynamic_routing_algo_to_update.description,\n kind: dynamic_routing_algo_to_update.kind,\n algorithm_data: serde_json::json!(config_to_update),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: dynamic_routing_algo_to_update.algorithm_for,\n };\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // redact cache for contract based routing configs\n let cache_key = format!(\n \"{}_{}\",\n profile_id.get_string_repr(),\n algorithm_id.get_string_repr()\n );\n let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache(\n cache_key.into(),\n )];\n let _ = cache::publish_into_redact_channel(\n state.store.get_cache_store().as_ref(),\n cache_entries_to_redact,\n )\n .await\n .map_err(|e| logger::error!(\"unable to publish into the redact channel for evicting the contract based routing config cache {e:?}\"));\n\n let new_record = record.foreign_into();\n\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_owned())),\n );\n\n let prefix_of_dynamic_routing_keys = helpers::generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n profile_id.get_string_repr(),\n );\n state\n .grpc_client\n .clone()\n .dynamic_routing\n .contract_based_client\n .clone()\n .async_map(|ct_client| async move {\n ct_client\n .invalidate_contracts(prefix_of_dynamic_routing_keys)\n .await\n .change_context(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"Failed to invalidate the routing keys\".to_string(),\n })\n })\n .await\n .transpose()?;\n\n Ok(service_api::ApplicationResponse::Json(new_record))\n}",
|
| 49 |
+
"diff_span": {
|
| 50 |
+
"before": ") -> RouterResponse<routing_types::RoutingDictionaryRecord> {\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([(\"profile_id\", profile_id.get_string_repr().to_owned())]),\n );\n let db = state.store.as_ref();\n\n let dynamic_routing_algo_to_update = db\n .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)\n .await\n .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;\n\n let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update\n .algorithm_data\n .parse_value::<routing::ContractBasedRoutingConfig>(\"ContractBasedRoutingConfig\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig\")?;\n\n config_to_update.update(request);\n\n let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n let algo = RoutingAlgorithm {\n algorithm_id: updated_algorithm_id,\n profile_id: dynamic_routing_algo_to_update.profile_id,\n merchant_id: dynamic_routing_algo_to_update.merchant_id,\n name: dynamic_routing_algo_to_update.name,\n description: dynamic_routing_algo_to_update.description,\n kind: dynamic_routing_algo_to_update.kind,\n algorithm_data: serde_json::json!(config_to_update),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: dynamic_routing_algo_to_update.algorithm_for,\n };\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // redact cache for contract based routing configs\n let cache_key = format!(\n \"{}_{}\",\n profile_id.get_string_repr(),\n algorithm_id.get_string_repr()\n );\n let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache(\n cache_key.into(),\n )];\n let _ = cache::publish_into_redact_channel(\n state.store.get_cache_store().as_ref(),\n cache_entries_to_redact,\n )\n .await\n .map_err(|e| logger::error!(\"unable to publish into the redact channel for evicting the contract based routing config cache {e:?}\"));\n\n let new_record = record.foreign_into();\n\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([(\"profile_id\", profile_id.get_string_repr().to_owned())]),\n );\n",
|
| 51 |
+
"after": " metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_owned())),\n );\n let db = state.store.as_ref();\n\n let dynamic_routing_algo_to_update = db\n .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)\n .await\n .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;\n\n let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update\n .algorithm_data\n .parse_value::<routing::ContractBasedRoutingConfig>(\"ContractBasedRoutingConfig\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig\")?;\n\n config_to_update.update(request);\n\n let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n let algo = RoutingAlgorithm {\n algorithm_id: updated_algorithm_id,\n profile_id: dynamic_routing_algo_to_update.profile_id,\n merchant_id: dynamic_routing_algo_to_update.merchant_id,\n name: dynamic_routing_algo_to_update.name,\n description: dynamic_routing_algo_to_update.description,\n kind: dynamic_routing_algo_to_update.kind,\n algorithm_data: serde_json::json!(config_to_update),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: dynamic_routing_algo_to_update.algorithm_for,\n };\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // redact cache for contract based routing configs\n let cache_key = format!(\n \"{}_{}\",\n profile_id.get_string_repr(),\n algorithm_id.get_string_repr()\n );\n let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache(\n cache_key.into(),\n )];\n let _ = cache::publish_into_redact_channel(\n state.store.get_cache_store().as_ref(),\n cache_entries_to_redact,\n )\n .await\n .map_err(|e| logger::error!(\"unable to publish into the redact channel for evicting the contract based routing config cache {e:?}\"));\n\n let new_record = record.foreign_into();\n\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_owned())),\n );\n"
|
| 52 |
+
},
|
| 53 |
+
"commit_sha": "584db459eed99bb47fe3ef79f0c23287c8701a15"
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing.rs::DynamicRoutingClientConfig::function::get_dynamic_routing_connection",
|
| 57 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 58 |
+
"kind": "function_item",
|
| 59 |
+
"status": "modified",
|
| 60 |
+
"code_changed": true,
|
| 61 |
+
"imports_changed": false,
|
| 62 |
+
"before_code": "pub async fn get_dynamic_routing_connection(\n self,\n client: Client,\n ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {\n let (success_rate_client, contract_based_client, elimination_based_client) = match self {\n Self::Enabled { host, port, .. } => {\n let uri = format!(\"http://{}:{}\", host, port).parse::<tonic::transport::Uri>()?;\n logger::info!(\"Connection established with dynamic routing gRPC Server\");\n (\n Some(SuccessRateCalculatorClient::with_origin(\n client.clone(),\n uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client, uri)),\n Some(EliminationAnalyserClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n elimination_rate_client,\n })\n }",
|
| 63 |
+
"after_code": "pub async fn get_dynamic_routing_connection(\n self,\n client: Client,\n ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {\n let (success_rate_client, contract_based_client, elimination_based_client) = match self {\n Self::Enabled { host, port, .. } => {\n let uri = format!(\"http://{}:{}\", host, port).parse::<tonic::transport::Uri>()?;\n logger::info!(\"Connection established with dynamic routing gRPC Server\");\n (\n Some(SuccessRateCalculatorClient::with_origin(\n client.clone(),\n uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client.clone(), uri.clone())),\n Some(EliminationAnalyserClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n elimination_rate_client: elimination_based_client,\n })\n }",
|
| 64 |
+
"diff_span": {
|
| 65 |
+
"before": " uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client, uri)),\n Some(EliminationAnalyserClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n elimination_rate_client,\n })\n }",
|
| 66 |
+
"after": " uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client.clone(), uri.clone())),\n Some(EliminationAnalyserClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n elimination_rate_client: elimination_based_client,\n })\n }"
|
| 67 |
+
},
|
| 68 |
+
"commit_sha": "584db459eed99bb47fe3ef79f0c23287c8701a15"
|
| 69 |
+
},
|
| 70 |
+
{
|
| 71 |
+
"id": "crates/router/src/core/routing.rs::function::contract_based_dynamic_routing_setup",
|
| 72 |
+
"file": "crates/router/src/core/routing.rs",
|
| 73 |
+
"kind": "function_item",
|
| 74 |
+
"status": "modified",
|
| 75 |
+
"code_changed": true,
|
| 76 |
+
"imports_changed": false,
|
| 77 |
+
"before_code": "pub async fn contract_based_dynamic_routing_setup(\n state: SessionState,\n key_store: domain::MerchantKeyStore,\n merchant_account: domain::MerchantAccount,\n profile_id: common_utils::id_type::ProfileId,\n feature_to_enable: routing_types::DynamicRoutingFeatures,\n config: routing_types::ContractBasedRoutingConfig,\n) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> {\n let db = state.store.as_ref();\n let key_manager_state = &(&state).into();\n\n let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n Some(&profile_id),\n merchant_account.get_id(),\n )\n .await?\n .get_required_value(\"Profile\")\n .change_context(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n // validate the contained mca_ids\n if let Some(info_vec) = &config.label_info {\n for info in info_vec {\n let mca = db\n .find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n key_manager_state,\n merchant_account.get_id(),\n &info.mca_id,\n &key_store,\n )\n .await\n .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: info.mca_id.get_string_repr().to_owned(),\n })?;\n\n utils::when(&mca.connector_name != &info.label, || {\n Err(errors::ApiErrorResponse::InvalidRequestData {\n message: \"Incorrect mca configuration received\".to_string(),\n })\n })?;\n }\n }\n\n let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize dynamic routing algorithm ref from business profile\",\n )\n .ok()\n .flatten();\n\n utils::when(\n dynamic_routing_algo_ref\n .as_mut()\n .map(|algo| {\n algo.contract_based_routing.as_mut().map(|contract_algo| {\n *contract_algo.get_enabled_features() == feature_to_enable\n && contract_algo\n .clone()\n .get_algorithm_id_with_timestamp()\n .algorithm_id\n .is_some()\n })\n })\n .flatten()\n .unwrap_or(false),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Contract Routing with specified features is already enabled\".to_string(),\n })\n },\n )?;\n\n let merchant_id = business_profile.merchant_id.clone();\n let algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n\n let algo = RoutingAlgorithm {\n algorithm_id: algorithm_id.clone(),\n profile_id: profile_id.clone(),\n merchant_id,\n name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),\n description: None,\n kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,\n algorithm_data: serde_json::json!(config),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: common_enums::TransactionType::Payment,\n };\n\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based\n // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up\n let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref {\n algo.update_algorithm_id(\n algorithm_id,\n feature_to_enable,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n );\n algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting);\n algo\n } else {\n let contract_algo = routing_types::ContractRoutingAlgorithm {\n algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(algorithm_id.clone()),\n timestamp: common_utils::date_time::now_unix_timestamp(),\n },\n enabled_feature: feature_to_enable,\n };\n let dynamic_routing_algo_ref = routing_types::DynamicRoutingAlgorithmRef {\n success_based_algorithm: None,\n elimination_routing_algorithm: None,\n dynamic_routing_volume_split: None,\n contract_based_routing: Some(contract_algo),\n };\n dynamic_routing_algo_ref\n };\n\n match feature_to_enable {\n routing::DynamicRoutingFeatures::Metrics\n | routing::DynamicRoutingFeatures::DynamicConnectorSelection => {\n helpers::update_business_profile_active_dynamic_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n final_algorithm,\n )\n .await?;\n\n // Should we also update at dynamic routing service?\n let new_record = record.foreign_into();\n\n metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([(\"profile_id\", profile_id.get_string_repr().to_string())]),\n );\n Ok(service_api::ApplicationResponse::Json(new_record))\n }\n routing::DynamicRoutingFeatures::None => {\n helpers::disable_dynamic_routing_algorithm(\n &state,\n key_store,\n business_profile,\n final_algorithm,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n )\n .await\n }\n }\n}",
|
| 78 |
+
"after_code": "pub async fn contract_based_dynamic_routing_setup(\n state: SessionState,\n key_store: domain::MerchantKeyStore,\n merchant_account: domain::MerchantAccount,\n profile_id: common_utils::id_type::ProfileId,\n feature_to_enable: routing_types::DynamicRoutingFeatures,\n config: routing_types::ContractBasedRoutingConfig,\n) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> {\n let db = state.store.as_ref();\n let key_manager_state = &(&state).into();\n\n let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(\n db,\n key_manager_state,\n &key_store,\n Some(&profile_id),\n merchant_account.get_id(),\n )\n .await?\n .get_required_value(\"Profile\")\n .change_context(errors::ApiErrorResponse::ProfileNotFound {\n id: profile_id.get_string_repr().to_owned(),\n })?;\n\n // validate the contained mca_ids\n if let Some(info_vec) = &config.label_info {\n for info in info_vec {\n let mca = db\n .find_by_merchant_connector_account_merchant_id_merchant_connector_id(\n key_manager_state,\n merchant_account.get_id(),\n &info.mca_id,\n &key_store,\n )\n .await\n .change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {\n id: info.mca_id.get_string_repr().to_owned(),\n })?;\n\n utils::when(&mca.connector_name != &info.label, || {\n Err(errors::ApiErrorResponse::InvalidRequestData {\n message: \"Incorrect mca configuration received\".to_string(),\n })\n })?;\n }\n }\n\n let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =\n business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to deserialize dynamic routing algorithm ref from business profile\",\n )\n .ok()\n .flatten();\n\n utils::when(\n dynamic_routing_algo_ref\n .as_mut()\n .map(|algo| {\n algo.contract_based_routing.as_mut().map(|contract_algo| {\n *contract_algo.get_enabled_features() == feature_to_enable\n && contract_algo\n .clone()\n .get_algorithm_id_with_timestamp()\n .algorithm_id\n .is_some()\n })\n })\n .flatten()\n .unwrap_or(false),\n || {\n Err(errors::ApiErrorResponse::PreconditionFailed {\n message: \"Contract Routing with specified features is already enabled\".to_string(),\n })\n },\n )?;\n\n let merchant_id = business_profile.merchant_id.clone();\n let algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n\n let algo = RoutingAlgorithm {\n algorithm_id: algorithm_id.clone(),\n profile_id: profile_id.clone(),\n merchant_id,\n name: helpers::CONTRACT_BASED_DYNAMIC_ROUTING_ALGORITHM.to_string(),\n description: None,\n kind: diesel_models::enums::RoutingAlgorithmKind::Dynamic,\n algorithm_data: serde_json::json!(config),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: common_enums::TransactionType::Payment,\n };\n\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // 1. if dynamic_routing_algo_ref already present, insert contract based algo and disable success based\n // 2. if dynamic_routing_algo_ref is not present, create a new dynamic_routing_algo_ref with contract algo set up\n let final_algorithm = if let Some(mut algo) = dynamic_routing_algo_ref {\n algo.update_algorithm_id(\n algorithm_id,\n feature_to_enable,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n );\n algo.disable_algorithm_id(routing_types::DynamicRoutingType::SuccessRateBasedRouting);\n algo\n } else {\n let contract_algo = routing_types::ContractRoutingAlgorithm {\n algorithm_id_with_timestamp: routing_types::DynamicAlgorithmWithTimestamp {\n algorithm_id: Some(algorithm_id.clone()),\n timestamp: common_utils::date_time::now_unix_timestamp(),\n },\n enabled_feature: feature_to_enable,\n };\n let dynamic_routing_algo_ref = routing_types::DynamicRoutingAlgorithmRef {\n success_based_algorithm: None,\n elimination_routing_algorithm: None,\n dynamic_routing_volume_split: None,\n contract_based_routing: Some(contract_algo),\n };\n dynamic_routing_algo_ref\n };\n\n match feature_to_enable {\n routing::DynamicRoutingFeatures::Metrics\n | routing::DynamicRoutingFeatures::DynamicConnectorSelection => {\n helpers::update_business_profile_active_dynamic_algorithm_ref(\n db,\n key_manager_state,\n &key_store,\n business_profile,\n final_algorithm,\n )\n .await?;\n\n // Should we also update at dynamic routing service?\n let new_record = record.foreign_into();\n\n metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_string())),\n );\n Ok(service_api::ApplicationResponse::Json(new_record))\n }\n routing::DynamicRoutingFeatures::None => {\n helpers::disable_dynamic_routing_algorithm(\n &state,\n key_store,\n business_profile,\n final_algorithm,\n routing_types::DynamicRoutingType::ContractBasedRouting,\n )\n .await\n }\n }\n}",
|
| 79 |
+
"diff_span": {
|
| 80 |
+
"before": "\n metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([(\"profile_id\", profile_id.get_string_repr().to_string())]),\n );\n Ok(service_api::ApplicationResponse::Json(new_record))",
|
| 81 |
+
"after": " metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_string())),\n );\n Ok(service_api::ApplicationResponse::Json(new_record))"
|
| 82 |
+
},
|
| 83 |
+
"commit_sha": "584db459eed99bb47fe3ef79f0c23287c8701a15"
|
| 84 |
+
}
|
| 85 |
+
]
|
| 86 |
+
}
|
diffs/pr_6761/59e573c/diff.json
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "59e573c3e34a99f9794795fa6d508059e737f7f8",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/api_models/src/routing.rs",
|
| 6 |
+
"crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs",
|
| 7 |
+
"crates/router/src/core/routing/helpers.rs"
|
| 8 |
+
],
|
| 9 |
+
"diffs": [
|
| 10 |
+
{
|
| 11 |
+
"id": "crates/router/src/core/routing/helpers.rs::function::push_metrics_with_update_window_for_contract_based_routing",
|
| 12 |
+
"file": "crates/router/src/core/routing/helpers.rs",
|
| 13 |
+
"kind": "function_item",
|
| 14 |
+
"status": "modified",
|
| 15 |
+
"code_changed": true,
|
| 16 |
+
"imports_changed": false,
|
| 17 |
+
"before_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id.clone(),\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ]),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n incremental_count: Some(1),\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n client\n .update_contracts(\n tenant_business_profile_id,\n vec![request_label_info],\n \"\".to_string(),\n vec![routing_types::RoutableConnectorChoiceWithStatus::new(\n routing_types::RoutableConnectorChoice {\n choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,\n connector: common_enums::RoutableConnectors::from_str(\n payment_connector.as_str(),\n )\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to infer routable_connector from connector\")?,\n merchant_connector_id: payment_attempt.merchant_connector_id.clone(),\n },\n payment_status_attribute == common_enums::AttemptStatus::Charged,\n )],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 18 |
+
"after_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"success_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve success_rate based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ]),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 19 |
+
"diff_span": {
|
| 20 |
+
"before": " let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id.clone(),\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_SUCCESS_BASED_ROUTING.add(\n &metrics::CONTEXT,\n 1,\n &add_attributes([\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ]),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n incremental_count: Some(1),\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n client\n .update_contracts(\n tenant_business_profile_id,\n vec![request_label_info],\n \"\".to_string(),\n vec![routing_types::RoutableConnectorChoiceWithStatus::new(\n routing_types::RoutableConnectorChoice {\n choice_kind: api_models::routing::RoutableChoiceKind::FullStruct,\n connector: common_enums::RoutableConnectors::from_str(\n payment_connector.as_str(),\n )\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to infer routable_connector from connector\")?,\n merchant_connector_id: payment_attempt.merchant_connector_id.clone(),\n },\n payment_status_attribute == common_enums::AttemptStatus::Charged,\n )],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n // final_label_info.current_count += 1;",
|
| 21 |
+
"after": " );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\"final_label_info - {:?}\", final_label_info);\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update success based routing window in dynamic routing service\",\n )?;\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),"
|
| 22 |
+
},
|
| 23 |
+
"commit_sha": "59e573c3e34a99f9794795fa6d508059e737f7f8"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs::impl::ProtoLabelInfo",
|
| 27 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs",
|
| 28 |
+
"kind": "impl_item",
|
| 29 |
+
"status": "modified",
|
| 30 |
+
"code_changed": true,
|
| 31 |
+
"imports_changed": false,
|
| 32 |
+
"before_code": "impl ForeignFrom<LabelInformation> for ProtoLabelInfo {\n fn foreign_from(config: LabelInformation) -> Self {\n Self {\n label: config.label,\n target_count: config.target_count,\n target_time: config.target_time,\n current_count: config.incremental_count.unwrap_or_default(),\n }\n }\n}",
|
| 33 |
+
"after_code": "impl ForeignFrom<LabelInformation> for ProtoLabelInfo {\n fn foreign_from(config: LabelInformation) -> Self {\n Self {\n label: config.label,\n target_count: config.target_count,\n target_time: config.target_time,\n current_count: 1,\n }\n }\n}",
|
| 34 |
+
"diff_span": {
|
| 35 |
+
"before": " target_count: config.target_count,\n target_time: config.target_time,\n current_count: config.incremental_count.unwrap_or_default(),\n }\n }",
|
| 36 |
+
"after": " target_count: config.target_count,\n target_time: config.target_time,\n current_count: 1,\n }\n }"
|
| 37 |
+
},
|
| 38 |
+
"commit_sha": "59e573c3e34a99f9794795fa6d508059e737f7f8"
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"id": "crates/api_models/src/routing.rs::struct::LabelInformation",
|
| 42 |
+
"file": "crates/api_models/src/routing.rs",
|
| 43 |
+
"kind": "struct_item",
|
| 44 |
+
"status": "modified",
|
| 45 |
+
"code_changed": true,
|
| 46 |
+
"imports_changed": false,
|
| 47 |
+
"before_code": "pub struct LabelInformation {\n pub label: String,\n pub target_count: u64,\n pub target_time: u64,\n pub incremental_count: Option<u64>,\n pub mca_id: common_utils::id_type::MerchantConnectorAccountId,\n}",
|
| 48 |
+
"after_code": "pub struct LabelInformation {\n pub label: String,\n pub target_count: u64,\n pub target_time: u64,\n pub mca_id: common_utils::id_type::MerchantConnectorAccountId,\n}",
|
| 49 |
+
"diff_span": {
|
| 50 |
+
"before": " pub target_count: u64,\n pub target_time: u64,\n pub incremental_count: Option<u64>,\n pub mca_id: common_utils::id_type::MerchantConnectorAccountId,\n}",
|
| 51 |
+
"after": ""
|
| 52 |
+
},
|
| 53 |
+
"commit_sha": "59e573c3e34a99f9794795fa6d508059e737f7f8"
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs::ProtoLabelInfo::function::foreign_from",
|
| 57 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing.rs",
|
| 58 |
+
"kind": "function_item",
|
| 59 |
+
"status": "modified",
|
| 60 |
+
"code_changed": true,
|
| 61 |
+
"imports_changed": false,
|
| 62 |
+
"before_code": "fn foreign_from(config: LabelInformation) -> Self {\n Self {\n label: config.label,\n target_count: config.target_count,\n target_time: config.target_time,\n current_count: config.incremental_count.unwrap_or_default(),\n }\n }",
|
| 63 |
+
"after_code": "fn foreign_from(config: LabelInformation) -> Self {\n Self {\n label: config.label,\n target_count: config.target_count,\n target_time: config.target_time,\n current_count: 1,\n }\n }",
|
| 64 |
+
"diff_span": {
|
| 65 |
+
"before": " target_count: config.target_count,\n target_time: config.target_time,\n current_count: config.incremental_count.unwrap_or_default(),\n }\n }",
|
| 66 |
+
"after": " target_count: config.target_count,\n target_time: config.target_time,\n current_count: 1,\n }\n }"
|
| 67 |
+
},
|
| 68 |
+
"commit_sha": "59e573c3e34a99f9794795fa6d508059e737f7f8"
|
| 69 |
+
}
|
| 70 |
+
]
|
| 71 |
+
}
|
diffs/pr_6761/5ec8b3f/diff.json
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 6 |
+
"crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 7 |
+
"crates/router/src/core/payments/routing.rs",
|
| 8 |
+
"crates/router/src/core/routing.rs",
|
| 9 |
+
"crates/router/src/core/routing/helpers.rs"
|
| 10 |
+
],
|
| 11 |
+
"diffs": [
|
| 12 |
+
{
|
| 13 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing.rs::impl::DynamicRoutingClientConfig",
|
| 14 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 15 |
+
"kind": "impl_item",
|
| 16 |
+
"status": "modified",
|
| 17 |
+
"code_changed": false,
|
| 18 |
+
"imports_changed": true,
|
| 19 |
+
"before_code": "impl DynamicRoutingClientConfig {\n /// establish connection with the server\n pub async fn get_dynamic_routing_connection(\n self,\n client: Client,\n ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {\n let (success_rate_client, contract_based_client) = match self {\n Self::Enabled { host, port, .. } => {\n let uri = format!(\"http://{}:{}\", host, port).parse::<tonic::transport::Uri>()?;\n logger::info!(\"Connection established with dynamic routing gRPC Server\");\n (\n Some(SuccessRateCalculatorClient::with_origin(\n client.clone(),\n uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n })\n }\n}",
|
| 20 |
+
"after_code": "impl DynamicRoutingClientConfig {\n /// establish connection with the server\n pub async fn get_dynamic_routing_connection(\n self,\n client: Client,\n ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {\n let (success_rate_client, contract_based_client) = match self {\n Self::Enabled { host, port, .. } => {\n let uri = format!(\"http://{}:{}\", host, port).parse::<tonic::transport::Uri>()?;\n logger::info!(\"Connection established with dynamic routing gRPC Server\");\n (\n Some(SuccessRateCalculatorClient::with_origin(\n client.clone(),\n uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n })\n }\n}",
|
| 21 |
+
"diff_span": {
|
| 22 |
+
"before": "",
|
| 23 |
+
"after": ""
|
| 24 |
+
},
|
| 25 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c",
|
| 26 |
+
"before_imports": [
|
| 27 |
+
"use api_models::routing::{\n CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,\n};",
|
| 28 |
+
"use super::Client;",
|
| 29 |
+
"use router_env::logger;",
|
| 30 |
+
"pub use contract_routing::ContractScoreCalculatorClient;"
|
| 31 |
+
],
|
| 32 |
+
"after_imports": [
|
| 33 |
+
"pub use contract_routing_client::ContractScoreCalculatorClient;",
|
| 34 |
+
"use api_models::routing::{\n CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,\n};",
|
| 35 |
+
"use router_env::logger;",
|
| 36 |
+
"use super::Client;"
|
| 37 |
+
]
|
| 38 |
+
},
|
| 39 |
+
{
|
| 40 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing.rs::DynamicRoutingClientConfig::function::get_dynamic_routing_connection",
|
| 41 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 42 |
+
"kind": "function_item",
|
| 43 |
+
"status": "modified",
|
| 44 |
+
"code_changed": false,
|
| 45 |
+
"imports_changed": true,
|
| 46 |
+
"before_code": "pub async fn get_dynamic_routing_connection(\n self,\n client: Client,\n ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {\n let (success_rate_client, contract_based_client) = match self {\n Self::Enabled { host, port, .. } => {\n let uri = format!(\"http://{}:{}\", host, port).parse::<tonic::transport::Uri>()?;\n logger::info!(\"Connection established with dynamic routing gRPC Server\");\n (\n Some(SuccessRateCalculatorClient::with_origin(\n client.clone(),\n uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n })\n }",
|
| 47 |
+
"after_code": "pub async fn get_dynamic_routing_connection(\n self,\n client: Client,\n ) -> Result<RoutingStrategy, Box<dyn std::error::Error>> {\n let (success_rate_client, contract_based_client) = match self {\n Self::Enabled { host, port, .. } => {\n let uri = format!(\"http://{}:{}\", host, port).parse::<tonic::transport::Uri>()?;\n logger::info!(\"Connection established with dynamic routing gRPC Server\");\n (\n Some(SuccessRateCalculatorClient::with_origin(\n client.clone(),\n uri.clone(),\n )),\n Some(ContractScoreCalculatorClient::with_origin(client, uri)),\n )\n }\n Self::Disabled => (None, None),\n };\n Ok(RoutingStrategy {\n success_rate_client,\n contract_based_client,\n })\n }",
|
| 48 |
+
"diff_span": {
|
| 49 |
+
"before": "",
|
| 50 |
+
"after": ""
|
| 51 |
+
},
|
| 52 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c",
|
| 53 |
+
"before_imports": [
|
| 54 |
+
"use api_models::routing::{\n CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,\n};",
|
| 55 |
+
"use super::Client;",
|
| 56 |
+
"use router_env::logger;",
|
| 57 |
+
"pub use contract_routing::ContractScoreCalculatorClient;"
|
| 58 |
+
],
|
| 59 |
+
"after_imports": [
|
| 60 |
+
"pub use contract_routing_client::ContractScoreCalculatorClient;",
|
| 61 |
+
"use api_models::routing::{\n CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,\n};",
|
| 62 |
+
"use router_env::logger;",
|
| 63 |
+
"use super::Client;"
|
| 64 |
+
]
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing.rs::struct::RoutingStrategy",
|
| 68 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 69 |
+
"kind": "struct_item",
|
| 70 |
+
"status": "modified",
|
| 71 |
+
"code_changed": false,
|
| 72 |
+
"imports_changed": true,
|
| 73 |
+
"before_code": "pub struct RoutingStrategy {\n /// success rate service for Dynamic Routing\n pub success_rate_client: Option<SuccessRateCalculatorClient<Client>>,\n /// contract based routing service for Dynamic Routing\n pub contract_based_client: Option<ContractScoreCalculatorClient<Client>>,\n}",
|
| 74 |
+
"after_code": "pub struct RoutingStrategy {\n /// success rate service for Dynamic Routing\n pub success_rate_client: Option<SuccessRateCalculatorClient<Client>>,\n /// contract based routing service for Dynamic Routing\n pub contract_based_client: Option<ContractScoreCalculatorClient<Client>>,\n}",
|
| 75 |
+
"diff_span": {
|
| 76 |
+
"before": "",
|
| 77 |
+
"after": ""
|
| 78 |
+
},
|
| 79 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c",
|
| 80 |
+
"before_imports": [
|
| 81 |
+
"use api_models::routing::{\n CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,\n};",
|
| 82 |
+
"use super::Client;",
|
| 83 |
+
"pub use contract_routing::ContractScoreCalculatorClient;"
|
| 84 |
+
],
|
| 85 |
+
"after_imports": [
|
| 86 |
+
"pub use contract_routing_client::ContractScoreCalculatorClient;",
|
| 87 |
+
"use api_models::routing::{\n CurrentBlockThreshold, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n SuccessBasedRoutingConfig, SuccessBasedRoutingConfigBody,\n};",
|
| 88 |
+
"use super::Client;"
|
| 89 |
+
]
|
| 90 |
+
},
|
| 91 |
+
{
|
| 92 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::impl::TimeScale",
|
| 93 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 94 |
+
"kind": "impl_item",
|
| 95 |
+
"status": "added",
|
| 96 |
+
"before_code": null,
|
| 97 |
+
"after_code": "impl ForeignFrom<ContractBasedTimeScale> for TimeScale {\n fn foreign_from(scale: ContractBasedTimeScale) -> Self {\n Self {\n time_scale: match scale {\n ContractBasedTimeScale::Day => 0,\n _ => 1,\n },\n }\n }\n}",
|
| 98 |
+
"diff_span": null,
|
| 99 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 100 |
+
},
|
| 101 |
+
{
|
| 102 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::impl::CalContractScoreConfig",
|
| 103 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 104 |
+
"kind": "impl_item",
|
| 105 |
+
"status": "added",
|
| 106 |
+
"before_code": null,
|
| 107 |
+
"after_code": "impl ForeignTryFrom<ContractBasedRoutingConfigBody> for CalContractScoreConfig {\n type Error = error_stack::Report<DynamicRoutingError>;\n fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config.time_scale.clone().map(TimeScale::foreign_from),\n })\n }\n}",
|
| 108 |
+
"diff_span": null,
|
| 109 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 110 |
+
},
|
| 111 |
+
{
|
| 112 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::ContractScoreCalculatorClient<Client>::function::update_contracts",
|
| 113 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 114 |
+
"kind": "function_item",
|
| 115 |
+
"status": "added",
|
| 116 |
+
"before_code": null,
|
| 117 |
+
"after_code": "async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }",
|
| 118 |
+
"diff_span": null,
|
| 119 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::CalContractScoreConfig::type::Error",
|
| 123 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 124 |
+
"kind": "type_item",
|
| 125 |
+
"status": "added",
|
| 126 |
+
"before_code": null,
|
| 127 |
+
"after_code": "type Error = error_stack::Report<DynamicRoutingError>;",
|
| 128 |
+
"diff_span": null,
|
| 129 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 130 |
+
},
|
| 131 |
+
{
|
| 132 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::CalContractScoreConfig::function::foreign_try_from",
|
| 133 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 134 |
+
"kind": "function_item",
|
| 135 |
+
"status": "added",
|
| 136 |
+
"before_code": null,
|
| 137 |
+
"after_code": "fn foreign_try_from(config: ContractBasedRoutingConfigBody) -> Result<Self, Self::Error> {\n Ok(Self {\n constants: config\n .constants\n .get_required_value(\"constants\")\n .change_context(DynamicRoutingError::MissingRequiredField {\n field: \"constants\".to_string(),\n })?,\n time_scale: config.time_scale.clone().map(TimeScale::foreign_from),\n })\n }",
|
| 138 |
+
"diff_span": null,
|
| 139 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 140 |
+
},
|
| 141 |
+
{
|
| 142 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::mod::contract_routing",
|
| 143 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 144 |
+
"kind": "mod_item",
|
| 145 |
+
"status": "added",
|
| 146 |
+
"before_code": null,
|
| 147 |
+
"after_code": "pub mod contract_routing {\n tonic::include_proto!(\"contract_routing\");\n}",
|
| 148 |
+
"diff_span": null,
|
| 149 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 150 |
+
},
|
| 151 |
+
{
|
| 152 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::ContractScoreCalculatorClient<Client>::function::invalidate_contracts",
|
| 153 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 154 |
+
"kind": "function_item",
|
| 155 |
+
"status": "added",
|
| 156 |
+
"before_code": null,
|
| 157 |
+
"after_code": "async fn invalidate_contracts(\n &self,\n id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let request = tonic::Request::new(InvalidateContractRequest { id });\n\n let response = self\n .clone()\n .invalidate_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to invalidate the contracts\".to_string(),\n ))?\n .into_inner();\n Ok(response)\n }",
|
| 158 |
+
"diff_span": null,
|
| 159 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::trait::ContractBasedDynamicRouting",
|
| 163 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 164 |
+
"kind": "trait_item",
|
| 165 |
+
"status": "added",
|
| 166 |
+
"before_code": null,
|
| 167 |
+
"after_code": "pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {\n /// To calculate the contract scores for the list of chosen connectors\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n ) -> DynamicRoutingResult<CalContractScoreResponse>;\n /// To update the contract scores with the given labels\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse>;\n /// To invalidates the contract scores against the id\n async fn invalidate_contracts(\n &self,\n id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse>;\n}",
|
| 168 |
+
"diff_span": null,
|
| 169 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::impl::ProtoLabelInfo",
|
| 173 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 174 |
+
"kind": "impl_item",
|
| 175 |
+
"status": "added",
|
| 176 |
+
"before_code": null,
|
| 177 |
+
"after_code": "impl ForeignFrom<LabelInformation> for ProtoLabelInfo {\n fn foreign_from(config: LabelInformation) -> Self {\n Self {\n label: config.label,\n target_count: config.target_count,\n target_time: config.target_time,\n current_count: 1,\n }\n }\n}",
|
| 178 |
+
"diff_span": null,
|
| 179 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::TimeScale::function::foreign_from",
|
| 183 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 184 |
+
"kind": "function_item",
|
| 185 |
+
"status": "added",
|
| 186 |
+
"before_code": null,
|
| 187 |
+
"after_code": "fn foreign_from(scale: ContractBasedTimeScale) -> Self {\n Self {\n time_scale: match scale {\n ContractBasedTimeScale::Day => 0,\n _ => 1,\n },\n }\n }",
|
| 188 |
+
"diff_span": null,
|
| 189 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing.rs::mod::contract_routing_client",
|
| 193 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 194 |
+
"kind": "mod_item",
|
| 195 |
+
"status": "added",
|
| 196 |
+
"before_code": null,
|
| 197 |
+
"after_code": "pub mod contract_routing_client;",
|
| 198 |
+
"diff_span": null,
|
| 199 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 200 |
+
},
|
| 201 |
+
{
|
| 202 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::ProtoLabelInfo::function::foreign_from",
|
| 203 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 204 |
+
"kind": "function_item",
|
| 205 |
+
"status": "added",
|
| 206 |
+
"before_code": null,
|
| 207 |
+
"after_code": "fn foreign_from(config: LabelInformation) -> Self {\n Self {\n label: config.label,\n target_count: config.target_count,\n target_time: config.target_time,\n current_count: 1,\n }\n }",
|
| 208 |
+
"diff_span": null,
|
| 209 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 210 |
+
},
|
| 211 |
+
{
|
| 212 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::impl::ContractScoreCalculatorClient<Client>",
|
| 213 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 214 |
+
"kind": "impl_item",
|
| 215 |
+
"status": "added",
|
| 216 |
+
"before_code": null,
|
| 217 |
+
"after_code": "impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> {\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n async fn invalidate_contracts(\n &self,\n id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let request = tonic::Request::new(InvalidateContractRequest { id });\n\n let response = self\n .clone()\n .invalidate_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to invalidate the contracts\".to_string(),\n ))?\n .into_inner();\n Ok(response)\n }\n}",
|
| 218 |
+
"diff_span": null,
|
| 219 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 220 |
+
},
|
| 221 |
+
{
|
| 222 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::ContractScoreCalculatorClient<Client>::function::calculate_contract_score",
|
| 223 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 224 |
+
"kind": "function_item",
|
| 225 |
+
"status": "added",
|
| 226 |
+
"before_code": null,
|
| 227 |
+
"after_code": "async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }",
|
| 228 |
+
"diff_span": null,
|
| 229 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 230 |
+
},
|
| 231 |
+
{
|
| 232 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing.rs::mod::contract_routing",
|
| 233 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing.rs",
|
| 234 |
+
"kind": "mod_item",
|
| 235 |
+
"status": "removed",
|
| 236 |
+
"before_code": "pub mod contract_routing;",
|
| 237 |
+
"after_code": null,
|
| 238 |
+
"diff_span": null,
|
| 239 |
+
"commit_sha": "5ec8b3fdbdf3b792d5c07713757fe3c795ed458c"
|
| 240 |
+
}
|
| 241 |
+
]
|
| 242 |
+
}
|
diffs/pr_6761/6241147/diff.json
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"commit_sha": "6241147ac9017f712f25e10fd7e63d912227f72f",
|
| 3 |
+
"pr_number": 6761,
|
| 4 |
+
"rust_files": [
|
| 5 |
+
"crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 6 |
+
"crates/router/src/core/payments/routing.rs",
|
| 7 |
+
"crates/router/src/core/routing.rs",
|
| 8 |
+
"crates/router/src/core/routing/helpers.rs"
|
| 9 |
+
],
|
| 10 |
+
"diffs": [
|
| 11 |
+
{
|
| 12 |
+
"id": "crates/router/src/core/routing/helpers.rs::function::push_metrics_with_update_window_for_contract_based_routing",
|
| 13 |
+
"file": "crates/router/src/core/routing/helpers.rs",
|
| 14 |
+
"kind": "function_item",
|
| 15 |
+
"status": "modified",
|
| 16 |
+
"code_changed": true,
|
| 17 |
+
"imports_changed": false,
|
| 18 |
+
"before_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"contract_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve contract based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\n \"contract based routing: matched LabelInformation - {:?}\",\n final_label_info\n );\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n if payment_status_attribute == common_enums::AttemptStatus::Charged {\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update contract based routing window in dynamic routing service\",\n )?;\n }\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n 1,\n router_env::metric_attributes!(\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 19 |
+
"after_code": "pub async fn push_metrics_with_update_window_for_contract_based_routing(\n state: &SessionState,\n payment_attempt: &storage::PaymentAttempt,\n routable_connectors: Vec<routing_types::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: DynamicRoutingConfigParamsInterpolator,\n) -> RouterResult<()> {\n let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile\n .dynamic_routing_algorithm\n .clone()\n .map(|val| val.parse_value(\"DynamicRoutingAlgorithmRef\"))\n .transpose()\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Failed to deserialize DynamicRoutingAlgorithmRef from JSON\")?\n .unwrap_or_default();\n\n let contract_routing_algo_ref = dynamic_routing_algo_ref\n .contract_based_routing\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"contract_routing_algorithm not found in dynamic_routing_algorithm from business_profile table\")?;\n\n if contract_routing_algo_ref.enabled_feature != routing_types::DynamicRoutingFeatures::None {\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .clone()\n .ok_or(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"contract_routing gRPC client not found\".to_string(),\n })?;\n\n let payment_connector = &payment_attempt.connector.clone().ok_or(\n errors::ApiErrorResponse::GenericNotFoundError {\n message: \"unable to derive payment connector from payment attempt\".to_string(),\n },\n )?;\n\n let contract_based_routing_config =\n fetch_dynamic_routing_configs::<routing_types::ContractBasedRoutingConfig>(\n state,\n business_profile,\n contract_routing_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"contract_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to retrieve contract based dynamic routing configs\")?;\n\n // check if this id is correct\n let tenant_business_profile_id = generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let mut existing_label_info = None;\n\n contract_based_routing_config\n .label_info\n .as_ref()\n .map(|label_info_vec| {\n for label_info in label_info_vec {\n if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n existing_label_info = Some(label_info.clone());\n }\n }\n });\n\n let final_label_info = existing_label_info\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to get LabelInformation from ContractBasedRoutingConfig\")?;\n\n logger::debug!(\n \"contract based routing: matched LabelInformation - {:?}\",\n final_label_info\n );\n\n let request_label_info = routing_types::LabelInformation {\n label: format!(\n \"{}:{}\",\n final_label_info.label.clone(),\n final_label_info.mca_id.get_string_repr()\n ),\n target_count: final_label_info.target_count,\n target_time: final_label_info.target_time,\n mca_id: final_label_info.mca_id.to_owned(),\n };\n\n let payment_status_attribute =\n get_desired_payment_status_for_success_routing_metrics(payment_attempt.status);\n\n if payment_status_attribute == common_enums::AttemptStatus::Charged {\n client\n .update_contracts(\n tenant_business_profile_id.clone(),\n vec![request_label_info],\n \"\".to_string(),\n vec![],\n state.get_grpc_headers(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update contract based routing window in dynamic routing service\",\n )?;\n }\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n state.get_grpc_headers(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to calculate/fetch contract scores from dynamic routing service\",\n )?;\n\n let first_contract_based_connector = &contract_scores\n .labels_with_score\n .first()\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to fetch the first connector from list of connectors obtained from dynamic routing service\",\n )?;\n\n let (first_contract_based_connector, connector_score, current_payment_cnt) = (first_contract_based_connector.label\n .split_once(':')\n .ok_or(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(format!(\n \"unable to split connector_name and mca_id from the first connector {:?} obtained from dynamic routing service\",\n first_contract_based_connector\n ))?\n .0, first_contract_based_connector.score, first_contract_based_connector.current_count );\n\n core_metrics::DYNAMIC_CONTRACT_BASED_ROUTING.add(\n 1,\n router_env::metric_attributes!(\n (\n \"tenant\",\n state.tenant.tenant_id.get_string_repr().to_owned(),\n ),\n (\n \"merchant_profile_id\",\n format!(\n \"{}:{}\",\n payment_attempt.merchant_id.get_string_repr(),\n payment_attempt.profile_id.get_string_repr()\n ),\n ),\n (\n \"contract_based_routing_connector\",\n first_contract_based_connector.to_string(),\n ),\n (\n \"contract_based_routing_connector_score\",\n connector_score.to_string(),\n ),\n (\n \"current_payment_count_contract_based_routing_connector\",\n current_payment_cnt.to_string(),\n ),\n (\"payment_connector\", payment_connector.to_string()),\n (\n \"currency\",\n payment_attempt\n .currency\n .map_or_else(|| \"None\".to_string(), |currency| currency.to_string()),\n ),\n (\n \"payment_method\",\n payment_attempt.payment_method.map_or_else(\n || \"None\".to_string(),\n |payment_method| payment_method.to_string(),\n ),\n ),\n (\n \"payment_method_type\",\n payment_attempt.payment_method_type.map_or_else(\n || \"None\".to_string(),\n |payment_method_type| payment_method_type.to_string(),\n ),\n ),\n (\n \"capture_method\",\n payment_attempt.capture_method.map_or_else(\n || \"None\".to_string(),\n |capture_method| capture_method.to_string(),\n ),\n ),\n (\n \"authentication_type\",\n payment_attempt.authentication_type.map_or_else(\n || \"None\".to_string(),\n |authentication_type| authentication_type.to_string(),\n ),\n ),\n (\"payment_status\", payment_attempt.status.to_string()),\n // (\"conclusive_classification\", outcome.to_string()),\n ),\n );\n logger::debug!(\"successfully pushed contract_based_routing metrics\");\n\n // let new_contract_config = routing_types::ContractBasedRoutingConfig {\n // params: contract_based_routing_config.params,\n // config: contract_based_routing_config.config,\n // label_info: Some(request_label_info),\n // };\n\n // final_label_info.current_count += 1;\n\n // contract_based_routing_config\n // .label_info\n // .map(|label_info_vec| {\n // for mut label_info in label_info_vec {\n // if Some(&label_info.mca_id) == payment_attempt.merchant_connector_id.as_ref() {\n // label_info = final_label_info.clone();\n // }\n // }\n // });\n\n Ok(())\n } else {\n Ok(())\n }\n}",
|
| 20 |
+
"diff_span": {
|
| 21 |
+
"before": "",
|
| 22 |
+
"after": " \"\".to_string(),\n vec![],\n state.get_grpc_headers(),\n )\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\n \"unable to update contract based routing window in dynamic routing service\",\n )?;\n }\n\n let contract_scores = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_config.clone(),\n \"\".to_string(),\n routable_connectors.clone(),\n state.get_grpc_headers(),\n )\n .await"
|
| 23 |
+
},
|
| 24 |
+
"commit_sha": "6241147ac9017f712f25e10fd7e63d912227f72f"
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"id": "crates/router/src/core/routing.rs::function::contract_based_routing_update_configs",
|
| 28 |
+
"file": "crates/router/src/core/routing.rs",
|
| 29 |
+
"kind": "function_item",
|
| 30 |
+
"status": "modified",
|
| 31 |
+
"code_changed": true,
|
| 32 |
+
"imports_changed": false,
|
| 33 |
+
"before_code": "pub async fn contract_based_routing_update_configs(\n state: SessionState,\n request: routing_types::ContractBasedRoutingConfig,\n algorithm_id: common_utils::id_type::RoutingId,\n profile_id: common_utils::id_type::ProfileId,\n) -> RouterResponse<routing_types::RoutingDictionaryRecord> {\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_owned())),\n );\n let db = state.store.as_ref();\n\n let dynamic_routing_algo_to_update = db\n .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)\n .await\n .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;\n\n let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update\n .algorithm_data\n .parse_value::<routing::ContractBasedRoutingConfig>(\"ContractBasedRoutingConfig\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig\")?;\n\n config_to_update.update(request);\n\n let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n let algo = RoutingAlgorithm {\n algorithm_id: updated_algorithm_id,\n profile_id: dynamic_routing_algo_to_update.profile_id,\n merchant_id: dynamic_routing_algo_to_update.merchant_id,\n name: dynamic_routing_algo_to_update.name,\n description: dynamic_routing_algo_to_update.description,\n kind: dynamic_routing_algo_to_update.kind,\n algorithm_data: serde_json::json!(config_to_update),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: dynamic_routing_algo_to_update.algorithm_for,\n };\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // redact cache for contract based routing configs\n let cache_key = format!(\n \"{}_{}\",\n profile_id.get_string_repr(),\n algorithm_id.get_string_repr()\n );\n let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache(\n cache_key.into(),\n )];\n let _ = cache::publish_into_redact_channel(\n state.store.get_cache_store().as_ref(),\n cache_entries_to_redact,\n )\n .await\n .map_err(|e| logger::error!(\"unable to publish into the redact channel for evicting the contract based routing config cache {e:?}\"));\n\n let new_record = record.foreign_into();\n\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_owned())),\n );\n\n let prefix_of_dynamic_routing_keys = helpers::generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n profile_id.get_string_repr(),\n );\n state\n .grpc_client\n .clone()\n .dynamic_routing\n .contract_based_client\n .clone()\n .async_map(|ct_client| async move {\n ct_client\n .invalidate_contracts(prefix_of_dynamic_routing_keys)\n .await\n .change_context(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"Failed to invalidate the contract based routing keys\".to_string(),\n })\n })\n .await\n .transpose()?;\n\n Ok(service_api::ApplicationResponse::Json(new_record))\n}",
|
| 34 |
+
"after_code": "pub async fn contract_based_routing_update_configs(\n state: SessionState,\n request: routing_types::ContractBasedRoutingConfig,\n algorithm_id: common_utils::id_type::RoutingId,\n profile_id: common_utils::id_type::ProfileId,\n) -> RouterResponse<routing_types::RoutingDictionaryRecord> {\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_owned())),\n );\n let db = state.store.as_ref();\n\n let dynamic_routing_algo_to_update = db\n .find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)\n .await\n .to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;\n\n let mut config_to_update: routing::ContractBasedRoutingConfig = dynamic_routing_algo_to_update\n .algorithm_data\n .parse_value::<routing::ContractBasedRoutingConfig>(\"ContractBasedRoutingConfig\")\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"unable to deserialize algorithm data from routing table into ContractBasedRoutingConfig\")?;\n\n config_to_update.update(request);\n\n let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();\n let timestamp = common_utils::date_time::now();\n let algo = RoutingAlgorithm {\n algorithm_id: updated_algorithm_id,\n profile_id: dynamic_routing_algo_to_update.profile_id,\n merchant_id: dynamic_routing_algo_to_update.merchant_id,\n name: dynamic_routing_algo_to_update.name,\n description: dynamic_routing_algo_to_update.description,\n kind: dynamic_routing_algo_to_update.kind,\n algorithm_data: serde_json::json!(config_to_update),\n created_at: timestamp,\n modified_at: timestamp,\n algorithm_for: dynamic_routing_algo_to_update.algorithm_for,\n };\n let record = db\n .insert_routing_algorithm(algo)\n .await\n .change_context(errors::ApiErrorResponse::InternalServerError)\n .attach_printable(\"Unable to insert record in routing algorithm table\")?;\n\n // redact cache for contract based routing configs\n let cache_key = format!(\n \"{}_{}\",\n profile_id.get_string_repr(),\n algorithm_id.get_string_repr()\n );\n let cache_entries_to_redact = vec![cache::CacheKind::ContractBasedDynamicRoutingCache(\n cache_key.into(),\n )];\n let _ = cache::publish_into_redact_channel(\n state.store.get_cache_store().as_ref(),\n cache_entries_to_redact,\n )\n .await\n .map_err(|e| logger::error!(\"unable to publish into the redact channel for evicting the contract based routing config cache {e:?}\"));\n\n let new_record = record.foreign_into();\n\n metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(\n 1,\n router_env::metric_attributes!((\"profile_id\", profile_id.get_string_repr().to_owned())),\n );\n\n let prefix_of_dynamic_routing_keys = helpers::generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n profile_id.get_string_repr(),\n );\n state\n .grpc_client\n .clone()\n .dynamic_routing\n .contract_based_client\n .clone()\n .async_map(|ct_client| async move {\n ct_client\n .invalidate_contracts(prefix_of_dynamic_routing_keys, state.get_grpc_headers())\n .await\n .change_context(errors::ApiErrorResponse::GenericNotFoundError {\n message: \"Failed to invalidate the contract based routing keys\".to_string(),\n })\n })\n .await\n .transpose()?;\n\n Ok(service_api::ApplicationResponse::Json(new_record))\n}",
|
| 35 |
+
"diff_span": {
|
| 36 |
+
"before": " .async_map(|ct_client| async move {\n ct_client\n .invalidate_contracts(prefix_of_dynamic_routing_keys)\n .await\n .change_context(errors::ApiErrorResponse::GenericNotFoundError {",
|
| 37 |
+
"after": " .async_map(|ct_client| async move {\n ct_client\n .invalidate_contracts(prefix_of_dynamic_routing_keys, state.get_grpc_headers())\n .await\n .change_context(errors::ApiErrorResponse::GenericNotFoundError {"
|
| 38 |
+
},
|
| 39 |
+
"commit_sha": "6241147ac9017f712f25e10fd7e63d912227f72f"
|
| 40 |
+
},
|
| 41 |
+
{
|
| 42 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::ContractScoreCalculatorClient<Client>::function::update_contracts",
|
| 43 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 44 |
+
"kind": "function_item",
|
| 45 |
+
"status": "modified",
|
| 46 |
+
"code_changed": true,
|
| 47 |
+
"imports_changed": true,
|
| 48 |
+
"before_code": "async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }",
|
| 49 |
+
"after_code": "async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let mut request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }",
|
| 50 |
+
"diff_span": {
|
| 51 |
+
"before": " .collect::<Vec<_>>();\n\n let request = tonic::Request::new(UpdateContractRequest {\n id,\n params,",
|
| 52 |
+
"after": " params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let mut request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self"
|
| 53 |
+
},
|
| 54 |
+
"commit_sha": "6241147ac9017f712f25e10fd7e63d912227f72f",
|
| 55 |
+
"before_imports": [
|
| 56 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 57 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 58 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 59 |
+
],
|
| 60 |
+
"after_imports": [
|
| 61 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 62 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 63 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 64 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 65 |
+
]
|
| 66 |
+
},
|
| 67 |
+
{
|
| 68 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::impl::ContractScoreCalculatorClient<Client>",
|
| 69 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 70 |
+
"kind": "impl_item",
|
| 71 |
+
"status": "modified",
|
| 72 |
+
"code_changed": true,
|
| 73 |
+
"imports_changed": true,
|
| 74 |
+
"before_code": "impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> {\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n async fn invalidate_contracts(\n &self,\n id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let request = tonic::Request::new(InvalidateContractRequest { id });\n\n let response = self\n .clone()\n .invalidate_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to invalidate the contracts\".to_string(),\n ))?\n .into_inner();\n Ok(response)\n }\n}",
|
| 75 |
+
"after_code": "impl ContractBasedDynamicRouting for ContractScoreCalculatorClient<Client> {\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let mut request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let mut request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n async fn invalidate_contracts(\n &self,\n id: String,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let mut request = tonic::Request::new(InvalidateContractRequest { id });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .invalidate_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to invalidate the contracts\".to_string(),\n ))?\n .into_inner();\n Ok(response)\n }\n}",
|
| 76 |
+
"diff_span": {
|
| 77 |
+
"before": " .transpose()?;\n\n let request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n async fn invalidate_contracts(\n &self,\n id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let request = tonic::Request::new(InvalidateContractRequest { id });\n\n let response = self",
|
| 78 |
+
"after": " params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let mut request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n _response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse> {\n let labels_information = label_info\n .into_iter()\n .map(ProtoLabelInfo::foreign_from)\n .collect::<Vec<_>>();\n\n let mut request = tonic::Request::new(UpdateContractRequest {\n id,\n params,\n labels_information,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .update_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to update the contracts\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }\n async fn invalidate_contracts(\n &self,\n id: String,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let mut request = tonic::Request::new(InvalidateContractRequest { id });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self"
|
| 79 |
+
},
|
| 80 |
+
"commit_sha": "6241147ac9017f712f25e10fd7e63d912227f72f",
|
| 81 |
+
"before_imports": [
|
| 82 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 83 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 84 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 85 |
+
],
|
| 86 |
+
"after_imports": [
|
| 87 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 88 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 89 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 90 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 91 |
+
]
|
| 92 |
+
},
|
| 93 |
+
{
|
| 94 |
+
"id": "crates/router/src/core/payments/routing.rs::function::perform_contract_based_routing",
|
| 95 |
+
"file": "crates/router/src/core/payments/routing.rs",
|
| 96 |
+
"kind": "function_item",
|
| 97 |
+
"status": "modified",
|
| 98 |
+
"code_changed": true,
|
| 99 |
+
"imports_changed": false,
|
| 100 |
+
"before_code": "pub async fn perform_contract_based_routing(\n state: &SessionState,\n routable_connectors: Vec<api_routing::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,\n contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,\n) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {\n if contract_based_algo_ref.enabled_feature\n == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection\n {\n logger::debug!(\n \"performing contract_based_routing for profile {}\",\n business_profile.get_id().get_string_repr()\n );\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .as_ref()\n .ok_or(errors::RoutingError::ContractRoutingClientInitializationError)\n .attach_printable(\"contract routing gRPC client not found\")?;\n\n let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<\n api_routing::ContractBasedRoutingConfig,\n >(\n state,\n business_profile,\n contract_based_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::RoutingError::GenericNotFoundError {\n field: \"contract_based_routing_algorithm_id\".to_string(),\n })\n .attach_printable(\n \"contract_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::RoutingError::ContractBasedRoutingConfigError)\n .attach_printable(\"unable to fetch contract based dynamic routing configs\")?;\n\n let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let contract_based_connectors: CalContractScoreResponse = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_configs,\n \"\".to_string(),\n routable_connectors,\n )\n .await\n .change_context(errors::RoutingError::ContractScoreCalculationError)\n .attach_printable(\n \"unable to calculate/fetch contract score from dynamic routing service\",\n )?;\n\n let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());\n\n for label_with_score in contract_based_connectors.labels_with_score {\n let (connector, merchant_connector_id) = label_with_score.label\n .split_once(':')\n .ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))\n .attach_printable(\n \"unable to split connector_name and mca_id from the label obtained by the dynamic routing service\",\n )?;\n\n connectors.push(api_routing::RoutableConnectorChoice {\n choice_kind: api_routing::RoutableChoiceKind::FullStruct,\n connector: common_enums::RoutableConnectors::from_str(connector)\n .change_context(errors::RoutingError::GenericConversionError {\n from: \"String\".to_string(),\n to: \"RoutableConnectors\".to_string(),\n })\n .attach_printable(\"unable to convert String to RoutableConnectors\")?,\n merchant_connector_id: Some(\n common_utils::id_type::MerchantConnectorAccountId::wrap(\n merchant_connector_id.to_string(),\n )\n .change_context(errors::RoutingError::GenericConversionError {\n from: \"String\".to_string(),\n to: \"MerchantConnectorAccountId\".to_string(),\n })\n .attach_printable(\"unable to convert MerchantConnectorAccountId from string\")?,\n ),\n });\n }\n\n logger::debug!(contract_based_routing_connectors=?connectors);\n Ok(connectors)\n } else {\n Ok(routable_connectors)\n }\n}",
|
| 101 |
+
"after_code": "pub async fn perform_contract_based_routing(\n state: &SessionState,\n routable_connectors: Vec<api_routing::RoutableConnectorChoice>,\n business_profile: &domain::Profile,\n _dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,\n contract_based_algo_ref: api_routing::ContractRoutingAlgorithm,\n) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>> {\n if contract_based_algo_ref.enabled_feature\n == api_routing::DynamicRoutingFeatures::DynamicConnectorSelection\n {\n logger::debug!(\n \"performing contract_based_routing for profile {}\",\n business_profile.get_id().get_string_repr()\n );\n let client = state\n .grpc_client\n .dynamic_routing\n .contract_based_client\n .as_ref()\n .ok_or(errors::RoutingError::ContractRoutingClientInitializationError)\n .attach_printable(\"contract routing gRPC client not found\")?;\n\n let contract_based_routing_configs = routing::helpers::fetch_dynamic_routing_configs::<\n api_routing::ContractBasedRoutingConfig,\n >(\n state,\n business_profile,\n contract_based_algo_ref\n .algorithm_id_with_timestamp\n .algorithm_id\n .ok_or(errors::RoutingError::GenericNotFoundError {\n field: \"contract_based_routing_algorithm_id\".to_string(),\n })\n .attach_printable(\n \"contract_based_routing_algorithm_id not found in business_profile\",\n )?,\n )\n .await\n .change_context(errors::RoutingError::ContractBasedRoutingConfigError)\n .attach_printable(\"unable to fetch contract based dynamic routing configs\")?;\n\n let tenant_business_profile_id = routing::helpers::generate_tenant_business_profile_id(\n &state.tenant.redis_key_prefix,\n business_profile.get_id().get_string_repr(),\n );\n\n let contract_based_connectors: CalContractScoreResponse = client\n .calculate_contract_score(\n tenant_business_profile_id,\n contract_based_routing_configs,\n \"\".to_string(),\n routable_connectors,\n state.get_grpc_headers(),\n )\n .await\n .change_context(errors::RoutingError::ContractScoreCalculationError)\n .attach_printable(\n \"unable to calculate/fetch contract score from dynamic routing service\",\n )?;\n\n let mut connectors = Vec::with_capacity(contract_based_connectors.labels_with_score.len());\n\n for label_with_score in contract_based_connectors.labels_with_score {\n let (connector, merchant_connector_id) = label_with_score.label\n .split_once(':')\n .ok_or(errors::RoutingError::InvalidContractBasedConnectorLabel(label_with_score.label.to_string()))\n .attach_printable(\n \"unable to split connector_name and mca_id from the label obtained by the dynamic routing service\",\n )?;\n\n connectors.push(api_routing::RoutableConnectorChoice {\n choice_kind: api_routing::RoutableChoiceKind::FullStruct,\n connector: common_enums::RoutableConnectors::from_str(connector)\n .change_context(errors::RoutingError::GenericConversionError {\n from: \"String\".to_string(),\n to: \"RoutableConnectors\".to_string(),\n })\n .attach_printable(\"unable to convert String to RoutableConnectors\")?,\n merchant_connector_id: Some(\n common_utils::id_type::MerchantConnectorAccountId::wrap(\n merchant_connector_id.to_string(),\n )\n .change_context(errors::RoutingError::GenericConversionError {\n from: \"String\".to_string(),\n to: \"MerchantConnectorAccountId\".to_string(),\n })\n .attach_printable(\"unable to convert MerchantConnectorAccountId from string\")?,\n ),\n });\n }\n\n logger::debug!(contract_based_routing_connectors=?connectors);\n Ok(connectors)\n } else {\n Ok(routable_connectors)\n }\n}",
|
| 102 |
+
"diff_span": {
|
| 103 |
+
"before": "",
|
| 104 |
+
"after": " \"\".to_string(),\n routable_connectors,\n state.get_grpc_headers(),\n )\n .await"
|
| 105 |
+
},
|
| 106 |
+
"commit_sha": "6241147ac9017f712f25e10fd7e63d912227f72f"
|
| 107 |
+
},
|
| 108 |
+
{
|
| 109 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::ContractScoreCalculatorClient<Client>::function::calculate_contract_score",
|
| 110 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 111 |
+
"kind": "function_item",
|
| 112 |
+
"status": "modified",
|
| 113 |
+
"code_changed": true,
|
| 114 |
+
"imports_changed": true,
|
| 115 |
+
"before_code": "async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }",
|
| 116 |
+
"after_code": "async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let mut request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .fetch_contract_score(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to fetch the contract score\".to_string(),\n ))?\n .into_inner();\n\n Ok(response)\n }",
|
| 117 |
+
"diff_span": {
|
| 118 |
+
"before": " .transpose()?;\n\n let request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,",
|
| 119 |
+
"after": " params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse> {\n let labels = label_input\n .into_iter()\n .map(|conn_choice| conn_choice.to_string())\n .collect::<Vec<_>>();\n\n let config = config\n .config\n .map(ForeignTryFrom::foreign_try_from)\n .transpose()?;\n\n let mut request = tonic::Request::new(CalContractScoreRequest {\n id,\n params,\n labels,\n config,\n });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self"
|
| 120 |
+
},
|
| 121 |
+
"commit_sha": "6241147ac9017f712f25e10fd7e63d912227f72f",
|
| 122 |
+
"before_imports": [
|
| 123 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 124 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 125 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 126 |
+
],
|
| 127 |
+
"after_imports": [
|
| 128 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 129 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 130 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 131 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 132 |
+
]
|
| 133 |
+
},
|
| 134 |
+
{
|
| 135 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::ContractScoreCalculatorClient<Client>::function::invalidate_contracts",
|
| 136 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 137 |
+
"kind": "function_item",
|
| 138 |
+
"status": "modified",
|
| 139 |
+
"code_changed": true,
|
| 140 |
+
"imports_changed": true,
|
| 141 |
+
"before_code": "async fn invalidate_contracts(\n &self,\n id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let request = tonic::Request::new(InvalidateContractRequest { id });\n\n let response = self\n .clone()\n .invalidate_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to invalidate the contracts\".to_string(),\n ))?\n .into_inner();\n Ok(response)\n }",
|
| 142 |
+
"after_code": "async fn invalidate_contracts(\n &self,\n id: String,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let mut request = tonic::Request::new(InvalidateContractRequest { id });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self\n .clone()\n .invalidate_contract(request)\n .await\n .change_context(DynamicRoutingError::ContractBasedRoutingFailure(\n \"Failed to invalidate the contracts\".to_string(),\n ))?\n .into_inner();\n Ok(response)\n }",
|
| 143 |
+
"diff_span": {
|
| 144 |
+
"before": " id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let request = tonic::Request::new(InvalidateContractRequest { id });\n\n let response = self",
|
| 145 |
+
"after": " &self,\n id: String,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<InvalidateContractResponse> {\n let mut request = tonic::Request::new(InvalidateContractRequest { id });\n\n request.add_headers_to_grpc_request(headers);\n\n let response = self"
|
| 146 |
+
},
|
| 147 |
+
"commit_sha": "6241147ac9017f712f25e10fd7e63d912227f72f",
|
| 148 |
+
"before_imports": [
|
| 149 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 150 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 151 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 152 |
+
],
|
| 153 |
+
"after_imports": [
|
| 154 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 155 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 156 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 157 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 158 |
+
]
|
| 159 |
+
},
|
| 160 |
+
{
|
| 161 |
+
"id": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs::trait::ContractBasedDynamicRouting",
|
| 162 |
+
"file": "crates/external_services/src/grpc_client/dynamic_routing/contract_routing_client.rs",
|
| 163 |
+
"kind": "trait_item",
|
| 164 |
+
"status": "modified",
|
| 165 |
+
"code_changed": true,
|
| 166 |
+
"imports_changed": true,
|
| 167 |
+
"before_code": "pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {\n /// To calculate the contract scores for the list of chosen connectors\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n ) -> DynamicRoutingResult<CalContractScoreResponse>;\n /// To update the contract scores with the given labels\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n response: Vec<RoutableConnectorChoiceWithStatus>,\n ) -> DynamicRoutingResult<UpdateContractResponse>;\n /// To invalidates the contract scores against the id\n async fn invalidate_contracts(\n &self,\n id: String,\n ) -> DynamicRoutingResult<InvalidateContractResponse>;\n}",
|
| 168 |
+
"after_code": "pub trait ContractBasedDynamicRouting: dyn_clone::DynClone + Send + Sync {\n /// To calculate the contract scores for the list of chosen connectors\n async fn calculate_contract_score(\n &self,\n id: String,\n config: ContractBasedRoutingConfig,\n params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse>;\n /// To update the contract scores with the given labels\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse>;\n /// To invalidates the contract scores against the id\n async fn invalidate_contracts(\n &self,\n id: String,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<InvalidateContractResponse>;\n}",
|
| 169 |
+
"diff_span": {
|
| 170 |
+
"before": "",
|
| 171 |
+
"after": " params: String,\n label_input: Vec<RoutableConnectorChoice>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<CalContractScoreResponse>;\n /// To update the contract scores with the given labels\n async fn update_contracts(\n &self,\n id: String,\n label_info: Vec<LabelInformation>,\n params: String,\n response: Vec<RoutableConnectorChoiceWithStatus>,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<UpdateContractResponse>;\n /// To invalidates the contract scores against the id\n async fn invalidate_contracts(\n &self,\n id: String,\n headers: GrpcHeaders,\n ) -> DynamicRoutingResult<InvalidateContractResponse>;\n}"
|
| 172 |
+
},
|
| 173 |
+
"commit_sha": "6241147ac9017f712f25e10fd7e63d912227f72f",
|
| 174 |
+
"before_imports": [
|
| 175 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 176 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 177 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 178 |
+
],
|
| 179 |
+
"after_imports": [
|
| 180 |
+
"use api_models::routing::{\n ContractBasedRoutingConfig, ContractBasedRoutingConfigBody, ContractBasedTimeScale,\n LabelInformation, RoutableConnectorChoice, RoutableConnectorChoiceWithStatus,\n};",
|
| 181 |
+
"use common_utils::{\n ext_traits::OptionExt,\n transformers::{ForeignFrom, ForeignTryFrom},\n};",
|
| 182 |
+
"use crate::grpc_client::{AddHeaders, GrpcHeaders};",
|
| 183 |
+
"use super::{Client, DynamicRoutingError, DynamicRoutingResult};"
|
| 184 |
+
]
|
| 185 |
+
}
|
| 186 |
+
]
|
| 187 |
+
}
|
diffs/pr_6761/6a01879/diff.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|