Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation
Rust adyenbeginner-friendlyfeaturedfinancefintechhacktoberfesthigh-performanceopen-sourceorchestrationpaymentpayment-gatewaypayment-integrationpayment-processingpaymentspayments-platformrestful-apirustsdkstripeworks-with-react
fix(offers): fail open on eligibility list failure and relax config (#14008)
Apoorv Dixitfb4c2c8b5fa9
diff --git a/config/config.example.toml b/config/config.example.tomlindex 50f032bac1..a13959b1cd 100644--- a/config/config.example.toml+++ b/config/config.example.toml@@ -1567,8 +1567,8 @@ backup_file_path = "./config/superposition_seed.toml" # Path to a local file for[offer_engine]base_url = "https://offer-engine.example.com/" # Base URL of the Offer Engine service-api_key = "" # API key for API-key authenticated Offer Engine calls-merchant_id = "" # Offer Engine merchant id sent in request bodies+api_key = "" # API key for the `application` credential source; omit when credentials are at the merchant level+merchant_id = "" # Offer Engine merchant id for the `application` credential source; omit when credentials are at the merchant level# Credentials and call settings for the Account Updater flow; omit the section entirely to keep it off[account_updater.juspay]diff --git a/crates/router/src/configs/secrets_transformers.rs b/crates/router/src/configs/secrets_transformers.rsindex aa885b7b31..75d7252a19 100644--- a/crates/router/src/configs/secrets_transformers.rs+++ b/crates/router/src/configs/secrets_transformers.rs@@ -376,9 +376,10 @@ impl SecretsHandler for settings::OfferEngineConfig {secret_management_client: &dyn SecretManagementInterface,) -> CustomResult<SecretStateContainer<Self, RawSecret>, SecretsManagementError> {let offer_engine = value.get_inner();- let api_key = secret_management_client- .get_secret(offer_engine.api_key.clone())- .await?;+ let api_key = match offer_engine.api_key.clone() {+ Some(api_key) => Some(secret_management_client.get_secret(api_key).await?),+ None => None,+ };Ok(value.transition_state(|offer_engine| Self {api_key,diff --git a/crates/router/src/configs/settings.rs b/crates/router/src/configs/settings.rsindex 1f319e9c25..baa1e89cde 100644--- a/crates/router/src/configs/settings.rs+++ b/crates/router/src/configs/settings.rs@@ -709,8 +709,8 @@ pub struct ForexApi {#[derive(Debug, Deserialize, Clone)]pub struct OfferEngineConfig {pub base_url: url::Url,- pub api_key: Secret<String>,- pub merchant_id: String,+ pub api_key: Option<Secret<String>>,+ pub merchant_id: Option<String>,}impl OfferEngineConfig {@@ -720,18 +720,28 @@ impl OfferEngineConfig {"offer_engine.base_url must end with a trailing slash".into(),))})?;- common_utils::fp_utils::when(self.api_key.peek().is_empty(), || {- Err(ApplicationError::InvalidConfigurationValueError(- "offer_engine.api_key must not be empty".into(),- ))- })?;- common_utils::fp_utils::when(self.merchant_id.is_empty(), || {- Err(error_stack::Report::from(- ApplicationError::InvalidConfigurationValueError(- "offer_engine.merchant_id must not be empty".into(),- ),- ))- })+ common_utils::fp_utils::when(+ self.api_key+ .as_ref()+ .is_some_and(|api_key| api_key.peek().is_empty()),+ || {+ Err(ApplicationError::InvalidConfigurationValueError(+ "offer_engine.api_key must not be empty".into(),+ ))+ },+ )?;+ common_utils::fp_utils::when(+ self.merchant_id+ .as_ref()+ .is_some_and(|merchant_id| merchant_id.is_empty()),+ || {+ Err(error_stack::Report::from(+ ApplicationError::InvalidConfigurationValueError(+ "offer_engine.merchant_id must not be empty".into(),+ ),+ ))+ },+ )}}diff --git a/crates/router/src/core/offer_engine.rs b/crates/router/src/core/offer_engine.rsindex 32c44a8649..858156c739 100644--- a/crates/router/src/core/offer_engine.rs+++ b/crates/router/src/core/offer_engine.rs@@ -12,6 +12,18 @@ pub mod velocity;pub use client::OfferEngineClient;pub use config::resolve_offer_engine_credential_source;++#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::EnumString)]+#[strum(serialize_all = "SCREAMING_SNAKE_CASE")]+pub enum SupportedPaymentMethodType {+ Card,+}++pub fn is_supported_payment_method_type(payment_method_type: &str) -> bool {+ payment_method_type+ .parse::<SupportedPaymentMethodType>()+ .is_ok()+}#[cfg(feature = "v1")]pub use notify::{schedule_payment_notification_for_attempt, schedule_refund_notification};pub use types::{OfferEngineCredentialSource, OfferEngineError, ResolvedOfferEngineConfig};diff --git a/crates/router/src/core/offer_engine/config.rs b/crates/router/src/core/offer_engine/config.rsindex 1d23562e64..a62323451e 100644--- a/crates/router/src/core/offer_engine/config.rs+++ b/crates/router/src/core/offer_engine/config.rs@@ -86,10 +86,24 @@ impl OfferEngineCredentialSource {})?.get_inner();+ let api_key = app_config.api_key.clone().ok_or_else(|| {+ error_stack::report!(OfferEngineError::MissingApplicationConfig(+ "offer_engine.api_key is required when credential source is application"+ .to_string()+ ))+ })?;++ let merchant_id = app_config.merchant_id.clone().ok_or_else(|| {+ error_stack::report!(OfferEngineError::MissingApplicationConfig(+ "offer_engine.merchant_id is required when credential source is application"+ .to_string()+ ))+ })?;+Ok(ResolvedOfferEngineConfig {base_url: app_config.base_url.clone(),- api_key: app_config.api_key.clone(),- merchant_id: app_config.merchant_id.clone(),+ api_key,+ merchant_id,})}diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex f0b1a945a5..04494a18d9 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -14951,11 +14951,10 @@ pub async fn payments_submit_eligibility(/// Resolve Offer Engine eligibility into `(amount_details, offer_details)` for the/// eligibility response.///-/// Both are `None` when eligibility is denied or Offer Engine is not available-/// (config resolution failures are treated as "offers not available"). A `/list`-/// failure while Offer Engine is enabled fails eligibility. When enabled but no-/// offer is selected, the payable amount is returned unchanged with an empty-/// offer list.+/// Both are `None` when eligibility is denied, the payment method is not one Offer+/// Engine serves, or Offer Engine is not available. A `/list` failure is failed+/// **open** (logged + metered, payable amount unchanged); `/apply` at confirm stays+/// fail-closed.#[cfg(all(feature = "oltp", feature = "v1"))]#[allow(clippy::too_many_arguments)]async fn resolve_offer_eligibility_details(@@ -14978,12 +14977,11 @@ async fn resolve_offer_eligibility_details(Option<api_models::payments::EligibilityAmountDetails>,Option<api_models::payments::EligibilityOfferDetails>,)> {- // Offers apply only when eligibility is not denied, an Offer Engine config- // resolves, and the currency is known (config-resolution failures are treated- // as "offers not available").let offer_context = if matches!(next_action,api_models::payments::NextActionCall::Deny { .. }+ ) || !offer_engine::is_supported_payment_method_type(+ &payment_method_type,) {None} else {@@ -15064,12 +15062,17 @@ async fn resolve_offer_eligibility_details(card_alias,};- // A `/list` failure while Offer Engine is enabled fails eligibility.let selected =offer_engine::eligibility::run_offer_eligibility(state, offer_config, ctx).await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Offer Engine /list failed")?;+ .unwrap_or_else(|error| {+ logger::warn!(+ ?error,+ "Offer Engine /list failed; proceeding without offers (fail-open)"+ );+ metrics::OFFER_ENGINE_LIST_FAILURES.add(1, &[]);+ None+ });match selected {// Enabled but no eligible offer: payable amount unchanged.@@ -15082,7 +15085,7 @@ async fn resolve_offer_eligibility_details(Some(api_models::payments::EligibilityOfferDetails::default()),)),// Eligible offer: store the quote for confirm to validate `/apply`- // against (keyed by offer id, the first-launch quote id; TTL kept).+ // against (keyed by a generated offer_quote_id; TTL kept).Some(selected) => {let processor_merchant_id = processor.get_account().get_id().clone();// Issue a unique quote id; confirm echoes it back to apply this offer.diff --git a/crates/router/src/routes/metrics.rs b/crates/router/src/routes/metrics.rsindex 2c0ad783af..e40c27ca1b 100644--- a/crates/router/src/routes/metrics.rs+++ b/crates/router/src/routes/metrics.rs@@ -234,6 +234,8 @@ counter_metric!(TASKS_ADDED_COUNT, GLOBAL_METER); // Tasks added to process traccounter_metric!(TASK_ADDITION_FAILURES_COUNT, GLOBAL_METER); // Failures in task addition to process trackercounter_metric!(TASKS_RESET_COUNT, GLOBAL_METER); // Tasks reset in process tracker for requeue flow+counter_metric!(OFFER_ENGINE_LIST_FAILURES, GLOBAL_METER);+// Offer Engine notification (Process Tracker) metricscounter_metric!(OFFER_ENGINE_NOTIFY_TASKS_SCHEDULED, GLOBAL_METER);counter_metric!(OFFER_ENGINE_NOTIFY_SCHEDULE_FAILURES, GLOBAL_METER);