Skip to content

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

feat(payments): keep the vault session and combined PML stable per payment (#14174)

Prasunna Soppac9cfc23f16a1
diff --git a/crates/api_models/src/payments.rs b/crates/api_models/src/payments.rs
index 569a0df631..aa00cdfa6d 100644
--- a/crates/api_models/src/payments.rs
+++ b/crates/api_models/src/payments.rs
@@ -10884,7 +10884,7 @@ pub enum SessionToken {
/// Top-level vault details returned in the session-tokens response.
/// For v1: contains both internal vault (SDK authorization) and external vault details.
/// For v2: contains only external vault details.
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct VaultDetails {
/// Internal vault details containing the SDK authorization token (v1 only)
pub internal_vault: Option<InternalVaultSessionDetails>,
@@ -10893,20 +10893,20 @@ pub struct VaultDetails {
}
/// Internal vault details for SDK authorization
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct InternalVaultSessionDetails {
/// Base64-encoded SDK authorization token for the internal vault session
pub sdk_authorization: String,
}
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case")]
pub enum VaultSessionDetails {
Vgs(VgsSessionDetails),
HyperswitchVault(HyperswitchVaultSessionDetails),
}
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct VgsSessionDetails {
/// The identifier of the external vault
#[schema(value_type = String)]
@@ -10915,7 +10915,7 @@ pub struct VgsSessionDetails {
pub sdk_env: String,
}
-#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)]
+#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct HyperswitchVaultSessionDetails {
/// Base64-encoded SDK authorization token for the Hyperswitch Vault session
#[schema(value_type = String)]
diff --git a/crates/common_utils/src/id_type/payment.rs b/crates/common_utils/src/id_type/payment.rs
index 759ab4f925..8d21cb8cb6 100644
--- a/crates/common_utils/src/id_type/payment.rs
+++ b/crates/common_utils/src/id_type/payment.rs
@@ -63,6 +63,29 @@ impl PaymentId {
)
}
+ /// Get the Redis key under which the payment-method vault session for this payment is cached
+ pub fn get_pm_vault_session_redis_key(&self, merchant_id: &super::MerchantId) -> String {
+ format!(
+ "{}_{}_pm_vault_session",
+ merchant_id.get_string_repr(),
+ self.get_string_repr()
+ )
+ }
+
+ /// Get the Redis key under which this payment's token for one saved payment method is pinned
+ pub fn get_pm_token_redis_key(
+ &self,
+ merchant_id: &super::MerchantId,
+ payment_method_id: &str,
+ ) -> String {
+ format!(
+ "{}_{}_{}_pm_token",
+ merchant_id.get_string_repr(),
+ self.get_string_repr(),
+ payment_method_id
+ )
+ }
+
/// Generate a test payment id with prefix test_
pub fn generate_test_payment_id_for_sample_data() -> Self {
let id = generate_id_with_default_len("test");
diff --git a/crates/payment_methods/src/client/session.rs b/crates/payment_methods/src/client/session.rs
index 3c891da83f..353d72da37 100644
--- a/crates/payment_methods/src/client/session.rs
+++ b/crates/payment_methods/src/client/session.rs
@@ -84,6 +84,9 @@ pub struct ModularPMSessionCreateResponse {
/// External vault session details returned by the PM service when an external vault is
/// configured for the profile.
pub external_vault_details: Option<VaultSessionDetailsResponse>,
+ /// When the session stops being usable on the PM service side.
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub expires_at: Option<time::PrimitiveDateTime>,
}
/// V1-facing response (thin wrapper around the wire response).
@@ -94,6 +97,7 @@ pub struct CreatePaymentMethodSessionResponse {
pub customer_id: Option<id_type::CustomerId>,
pub sdk_authorization: Option<String>,
pub external_vault_details: Option<api_models::payments::VaultSessionDetails>,
+ pub expires_at: Option<time::PrimitiveDateTime>,
}
// --- Conversions ---
@@ -119,6 +123,7 @@ impl TryFrom<ModularPMSessionCreateResponse> for CreatePaymentMethodSessionRespo
customer_id: resp.customer_id,
sdk_authorization: resp.sdk_authorization,
external_vault_details: resp.external_vault_details.map(Into::into),
+ expires_at: resp.expires_at,
})
}
}
diff --git a/crates/router/src/core/payment_methods/client.rs b/crates/router/src/core/payment_methods/client.rs
index 5e0d5d64bb..c92aa1224a 100644
--- a/crates/router/src/core/payment_methods/client.rs
+++ b/crates/router/src/core/payment_methods/client.rs
@@ -27,6 +27,7 @@ use crate::{
cards, transformers::list_customer_payment_methods_from_modular_service,
},
payments::helpers,
+ utils as core_utils,
},
pii::PeekInterface,
routes::{self, payment_methods::ParentPaymentMethodToken},
@@ -37,10 +38,56 @@ use crate::{
},
};
+/// How far ahead of the payment tokens a token pin is expired.
+///
+/// A pin that outlived the token it names would hand out a token the token store has already
+/// forgotten. Both are written within the same build, so a small margin is enough.
+const PIN_EXPIRY_MARGIN_IN_SECS: i64 = 5;
+
// ---------------------------------------------------------------------------
// Trait: CustomerPaymentMethodsFetcher
// ---------------------------------------------------------------------------
+/// Hands back the payment token this payment has already agreed on for `payment_method_id`,
+/// pinning `payment_token` as that token when this is the first call to get there.
+///
+/// The token is the one part of a listing that is newly generated on every call; pinning it —
+/// rather than caching the built listing — is what lets two calls for a payment agree without
+/// ever serving a list that outlived the configuration it was built from.
+///
+/// The pin is a single writer: whichever call stores its token first wins, and a call racing it
+/// reads that token back instead of its own, so concurrent callers answer with the same token.
+/// Both tokens resolve to the same saved payment method, so the one that loses is simply unused.
+///
+/// The pin expires a little before the token itself does, so it can never name a token the token
+/// store has already forgotten. Without a payment there is nothing to pin against, and the freshly
+/// generated token is returned unchanged.
+async fn pinned_payment_token(
+ state: &routes::SessionState,
+ payment_intent: Option<&storage::PaymentIntent>,
+ payment_method_id: &str,
+ payment_token: String,
+ intent_fulfillment_time: i64,
+) -> String {
+ match payment_intent {
+ None => payment_token,
+ Some(payment_intent) => {
+ let redis_key = payment_intent
+ .payment_id
+ .get_pm_token_redis_key(&payment_intent.processor_merchant_id, payment_method_id);
+
+ core_utils::pin_value(
+ state,
+ &redis_key,
+ "PinnedPaymentToken",
+ payment_token,
+ intent_fulfillment_time.saturating_sub(PIN_EXPIRY_MARGIN_IN_SECS),
+ )
+ .await
+ }
+ }
+}
+
/// Abstraction over saved-PM retrieval — allows future swap to a remote PM service.
#[async_trait::async_trait]
pub trait CustomerPaymentMethodsFetcher: Send + Sync {
@@ -87,7 +134,12 @@ fn to_client_pm(pm: CustomerPaymentMethod) -> CustomerPaymentMethodForClient {
}
/// DB-backed implementation — delegates to `cards::list_customer_payment_method`.
-pub struct DbCustomerPaymentMethodsFetcher;
+///
+/// `intent_fulfillment_time` is the window `cards::list_customer_payment_method` stores its
+/// tokens for; it is carried here so a token pin cannot outlive the token it names.
+pub struct DbCustomerPaymentMethodsFetcher {
+ pub intent_fulfillment_time: i64,
+}
#[async_trait::async_trait]
impl CustomerPaymentMethodsFetcher for DbCustomerPaymentMethodsFetcher {
@@ -118,11 +170,28 @@ impl CustomerPaymentMethodsFetcher for DbCustomerPaymentMethodsFetcher {
}
};
- Ok(response_body
- .customer_payment_methods
- .into_iter()
- .map(to_client_pm)
- .collect())
+ let intent_fulfillment_time = self.intent_fulfillment_time;
+
+ Ok(
+ futures::future::join_all(response_body.customer_payment_methods.into_iter().map(
+ |payment_method| async move {
+ let payment_token = pinned_payment_token(
+ state,
+ payment_intent,
+ &payment_method.payment_method_id,
+ payment_method.payment_token,
+ intent_fulfillment_time,
+ )
+ .await;
+
+ to_client_pm(CustomerPaymentMethod {
+ payment_token,
+ ..payment_method
+ })
+ },
+ ))
+ .await,
+ )
}
}
@@ -183,7 +252,7 @@ impl CustomerPaymentMethodsFetcher for ModularCustomerPaymentMethodsFetcher {
&self,
state: &routes::SessionState,
platform: &domain::Platform,
- _payment_intent: Option<&storage::PaymentIntent>,
+ payment_intent: Option<&storage::PaymentIntent>,
_payment_attempt: Option<&storage::PaymentAttempt>,
customer: &domain::Customer,
dimensions: &dimension_state::DimensionsWithProcessorAndProviderMerchantId,
@@ -269,6 +338,14 @@ impl CustomerPaymentMethodsFetcher for ModularCustomerPaymentMethodsFetcher {
self.intent_fulfillment_time,
)
.await?;
+ let payment_token = pinned_payment_token(
+ state,
+ payment_intent,
+ &pm.id,
+ payment_token,
+ self.intent_fulfillment_time,
+ )
+ .await;
// Build the client-facing response item.
let payment_method_data = pm.payment_method_data.and_then(|d| d.into());
@@ -613,16 +690,21 @@ async fn fetch_customer_payment_methods(
.await
} else {
logger::info!("Fetching customer payment methods from DB");
- DbCustomerPaymentMethodsFetcher
- .fetch(
- state,
- platform,
- Some(&payment_intent_context.payment_intent),
- Some(&payment_intent_context.payment_attempt),
- customer,
- &dimensions,
- )
- .await
+ DbCustomerPaymentMethodsFetcher {
+ intent_fulfillment_time: payment_intent_context
+ .business_profile
+ .get_order_fulfillment_time()
+ .unwrap_or(consts::DEFAULT_INTENT_FULFILLMENT_TIME),
+ }
+ .fetch(
+ state,
+ platform,
+ Some(&payment_intent_context.payment_intent),
+ Some(&payment_intent_context.payment_attempt),
+ customer,
+ &dimensions,
+ )
+ .await
}
}
}
diff --git a/crates/router/src/core/payments/types.rs b/crates/router/src/core/payments/types.rs
index 0618696934..a1f30e9049 100644
--- a/crates/router/src/core/payments/types.rs
+++ b/crates/router/src/core/payments/types.rs
@@ -19,6 +19,7 @@ use crate::{
core::errors::{self, RouterResult},
routes::SessionState,
types::{
+ self,
domain::Profile,
storage::{self, enums as storage_enums},
transformers::ForeignTryFrom,
@@ -474,3 +475,21 @@ impl ForeignTryFrom<&api_models::payments::ExternalThreeDsData> for Authenticati
})
}
}
+
+/// What the internal PM service handed back for a freshly created payment-method vault session.
+#[cfg(feature = "v1")]
+pub struct CreatedPmVaultSession {
+ pub vault_details: Option<types::api::VaultDetails>,
+ pub expires_at: Option<time::PrimitiveDateTime>,
+}
+
+/// The vault session cached per payment, so every call for that payment hands the SDK the same
+/// authorization. `customer_id` and `storage_type` travel with it so an intent update that
+/// changes either mints a fresh session instead of reusing one created under different terms.
+#[cfg(feature = "v1")]
+#[derive(Debug, serde::Serialize, serde::Deserialize)]
+pub struct CachedPmVaultSession {
+ pub customer_id: Option<common_utils::id_type::CustomerId>,
+ pub storage_type: common_enums::StorageType,
+ pub vault_details: types::api::VaultDetails,
+}
diff --git a/crates/router/src/core/payments/update_context.rs b/crates/router/src/core/payments/update_context.rs
index 2fea73ac0a..aff3066a14 100644
--- a/crates/router/src/core/payments/update_context.rs
+++ b/crates/router/src/core/payments/update_context.rs
@@ -234,7 +234,9 @@ async fn session_tokens(
.await?;
// Returned whole: the caller gets `session_token` and `vault_details` (the internal vault
- // SDK authorization) exactly as the standalone endpoint would have returned them.
+ // SDK authorization) exactly as the standalone endpoint would have returned them. The vault
+ // session is the per-payment one shared with `/session_tokens`, so a server integration sees
+ // the same SDK authorization on every call for this payment.
json_body(response, "session_tokens")
}
diff --git a/crates/router/src/core/payments/vault_session.rs b/crates/router/src/core/payments/vault_session.rs
index 6f798a6d40..bbbc284c03 100644
--- a/crates/router/src/core/payments/vault_session.rs
+++ b/crates/router/src/core/payments/vault_session.rs
@@ -33,6 +33,14 @@ use crate::core::{
payments::{customers, gateway::context as gateway_context},
utils as core_utils,
};
+#[cfg(feature = "v1")]
+use crate::{
+ consts,
+ core::{
+ payments::types::{CachedPmVaultSession, CreatedPmVaultSession},
+ utils as core_utils,
+ },
+};
use crate::{
core::{
errors::{self, RouterResult},
@@ -108,6 +116,113 @@ where
Ok(())
}
+/// Storage intent for the PM vault session.
+///
+/// `setup_future_usage` on the intent carries the merchant's storage intent for the session: set
+/// (on_session/off_session) → persistent, absent → volatile. Persistent intent without a
+/// customer_id is rejected at payment create/confirm (`validate_customer_id_mandatory_cases`), so
+/// a persistent session always has a customer to attach to.
+#[cfg(feature = "v1")]
+pub fn resolve_vault_storage_type(
+ setup_future_usage: Option<common_enums::FutureUsage>,
+ customer_id: Option<&id_type::CustomerId>,
+) -> common_enums::StorageType {
+ match (setup_future_usage, customer_id) {
+ (Some(_), Some(_)) => common_enums::StorageType::Persistent,
+ _ => common_enums::StorageType::Volatile,
+ }
+}
+
+/// Returns the PM vault session for this payment, creating it on first use.
+///
+/// Every route that mints session tokens for a payment — the standalone session-tokens call and
+/// the server-integration enrichment of a payment create or intent update — comes through here,
+/// so all of them return the session minted by whichever ran first. The cache lives no longer
+/// than the PM service says the session does. A cache miss or a cache write failure is never
+/// fatal: the worst case is a fresh session, which is what every call used to get.
+#[cfg(feature = "v1")]
+pub async fn get_or_create_pm_vault_session(
+ state: &SessionState,
+ external_vault_profile: &domain::Profile,
+ processor_merchant_id: &id_type::MerchantId,
+ payment_id: &id_type::PaymentId,
+ customer_id: Option<&id_type::CustomerId>,
+ storage_type: common_enums::StorageType,
+) -> RouterResult<Option<api::VaultDetails>> {
+ let redis_key = payment_id.get_pm_vault_session_redis_key(processor_merchant_id);
+
+ let cached = core_utils::read_cached_value::<CachedPmVaultSession>(
+ state,
+ &redis_key,
+ "CachedPmVaultSession",
+ )
+ .await
+ .filter(|cached| {
+ cached.customer_id.as_ref() == customer_id && cached.storage_type == storage_type
+ });
+
+ match cached {
+ Some(cached) => {
+ router_env::logger::info!(
+ payment_id = %payment_id.get_string_repr(),
+ ?storage_type,
+ "Reusing the cached PM vault session for this payment"
+ );
+ Ok(Some(cached.vault_details))
+ }
+ None => {
+ let created = call_internal_pm_session_create_for_vault(
+ state,
+ external_vault_profile,
+ customer_id,
+ storage_type,
+ )
+ .await?;
+
+ let cache_entry = created
+ .vault_details
+ .clone()
+ .zip(cache_ttl_seconds(created.expires_at))
+ .map(|(vault_details, ttl_seconds)| {
+ (
+ CachedPmVaultSession {
+ customer_id: customer_id.cloned(),
+ storage_type,
+ vault_details,
+ },
+ ttl_seconds,
+ )
+ });
+
+ if let Some((entry, ttl_seconds)) = cache_entry {
+ core_utils::cache_value_with_expiry(
+ state,
+ &redis_key,
+ "CachedPmVaultSession",
+ &entry,
+ ttl_seconds,
+ )
+ .await;
+ }
+
+ Ok(created.vault_details)
+ }
+ }
+}
+
+/// How long the cache entry may live: the remaining life of the PM session, capped at the
+/// default session expiry. `None` when the session has already expired, in which case caching
+/// would only hand out a dead authorization.
+#[cfg(feature = "v1")]
+fn cache_ttl_seconds(expires_at: Option<time::PrimitiveDateTime>) -> Option<i64> {
+ let default_ttl = i64::from(consts::DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY);
+ expires_at
+ .map(|expires_at| (expires_at - common_utils::date_time::now()).whole_seconds())
+ .map_or(Some(default_ttl), |remaining| {
+ Some(remaining.min(default_ttl)).filter(|ttl| *ttl > 0)
+ })
+}
+
/// Call the internal payment-methods service to create a PM session and extract both
/// `internal_vault` (sdk_authorization) and `external_vault_details` from the response.
#[cfg(feature = "v1")]
@@ -116,7 +231,7 @@ async fn call_internal_pm_session_create_for_vault(
profile: &domain::Profile,
customer_id: Option<&id_type::CustomerId>,
storage_type: common_enums::StorageType,
-) -> RouterResult<Option<api::VaultDetails>> {
+) -> RouterResult<CreatedPmVaultSession> {
use common_utils::request::Headers;
use payment_methods::client::{
CreatePaymentMethodSession, CreatePaymentMethodSessionV1Request, PaymentMethodClient,
@@ -179,32 +294,37 @@ async fn call_internal_pm_session_create_for_vault(
sdk_authorization: sdk_auth,
});
- let external_vault_details = response.external_vault_details;
-
- // Only return Some if at least one of the two parts is present.
- if internal_vault.is_none() && external_vault_details.is_none() {
- router_env::logger::warn!(
- merchant_id=%merchant_id.get_string_repr(),
- profile_id=%profile_id.get_string_repr(),
- ?storage_type,
- "Internal PM session create returned neither sdk_authorization nor external_vault_details"
- );
- return Ok(None);
- }
-
- router_env::logger::info!(
- merchant_id=%merchant_id.get_string_repr(),
- profile_id=%profile_id.get_string_repr(),
- ?storage_type,
- has_internal_vault=internal_vault.is_some(),
- has_external_vault_details=external_vault_details.is_some(),
- "Internal PM session create for vault succeeded"
- );
+ // Only worth returning when at least one of the two parts is present.
+ let vault_details = match (internal_vault, response.external_vault_details) {
+ (None, None) => {
+ router_env::logger::warn!(
+ merchant_id=%merchant_id.get_string_repr(),
+ profile_id=%profile_id.get_string_repr(),
+ ?storage_type,
+ "Internal PM session create returned neither sdk_authorization nor external_vault_details"
+ );
+ None
+ }
+ (internal_vault, external_vault_details) => {
+ router_env::logger::info!(
+ merchant_id=%merchant_id.get_string_repr(),
+ profile_id=%profile_id.get_string_repr(),
+ ?storage_type,
+ has_internal_vault=internal_vault.is_some(),
+ has_external_vault_details=external_vault_details.is_some(),
+ "Internal PM session created for vault details"
+ );
+ Some(api::VaultDetails {
+ internal_vault,
+ external_vault_details,
+ })
+ }
+ };
- Ok(Some(api::VaultDetails {
- internal_vault,
- external_vault_details,
- }))
+ Ok(CreatedPmVaultSession {
+ vault_details,
+ expires_at: response.expires_at,
+ })
}
#[cfg(feature = "v1")]
@@ -237,31 +357,32 @@ where
helpers::resolve_provider_profile(state, platform, profile).await?;
let customer_id = customer.as_ref().map(|c| c.get_id());
- // `setup_future_usage` on the intent carries the merchant's storage intent for the
- // session: set (on_session/off_session) → persistent, absent → volatile. Persistent
- // intent without a customer_id is rejected at payment create/confirm
- // (`validate_customer_id_mandatory_cases`), so a persistent session always has a
- // customer to attach to.
- let storage_type = match (
- payment_data.get_payment_intent().setup_future_usage,
- customer_id,
- ) {
- (Some(_), Some(_)) => common_enums::StorageType::Persistent,
- _ => common_enums::StorageType::Volatile,
- };
+ let payment_intent = payment_data.get_payment_intent();
+ let payment_id = payment_intent.payment_id.clone();
+ let setup_future_usage = payment_intent.setup_future_usage;
+
+ // A payment is unique under its processor merchant — that is the pair every lookup of it
+ // uses — so that is what namespaces the cache. The intent's own `merchant_id` is the
+ // provider merchant, which in a platform flow is shared by every connected merchant under
+ // it: two of them picking the same `payment_id` would collide on one cached session.
+ let processor_merchant_id = platform.get_processor().get_account().get_id().clone();
+
+ let storage_type = resolve_vault_storage_type(setup_future_usage, customer_id);
router_env::logger::info!(
?storage_type,
- setup_future_usage=?payment_data.get_payment_intent().setup_future_usage,
- has_customer=customer_id.is_some(),
+ ?setup_future_usage,
+ has_customer = customer_id.is_some(),
"Resolved storage type for PM vault session create"
);
// Use the resolved external vault profile (the platform merchant's profile in platform
// flows) so the PM service operates under the merchant that actually holds the external
// vault configuration. For standard merchants this is the payment profile itself.
- let vault_details = call_internal_pm_session_create_for_vault(
+ let vault_details = get_or_create_pm_vault_session(
state,
&external_vault_profile,
+ &processor_merchant_id,
+ &payment_id,
customer_id,
storage_type,
)
diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rs
index 6e78576cd4..b1c4e25084 100644
--- a/crates/router/src/core/utils.rs
+++ b/crates/router/src/core/utils.rs
@@ -41,6 +41,7 @@ use hyperswitch_masking::Secret;
#[cfg(feature = "payouts")]
use hyperswitch_masking::{ExposeInterface, PeekInterface};
use maud::{html, PreEscaped};
+use redis_interface::errors::RedisError;
use regex::Regex;
use router_env::{instrument, tracing};
use storage_impl::StorageError;
@@ -3171,3 +3172,121 @@ where
Ok(encrypted_data)
}
+
+/// Reads a value cached in Redis under `redis_key`.
+///
+/// Never fatal: a miss, an unreachable Redis, or an entry that no longer deserializes all read as
+/// "not cached", and the caller rebuilds what it would have built without the cache. Only the
+/// failures are logged; a miss is the normal first-call case.
+pub async fn read_cached_value<T>(
+ state: &SessionState,
+ redis_key: &str,
+ type_name: &'static str,
+) -> Option<T>
+where
+ T: serde::de::DeserializeOwned,
+{
+ let lookup: CustomResult<T, RedisError> = async {
+ state
+ .store
+ .get_redis_conn()?
+ .get_and_deserialize_key::<T>(&redis_key.into(), type_name)
+ .await
+ }
+ .await;
+
+ match lookup {
+ Ok(cached) => Some(cached),
+ Err(err) if matches!(err.current_context(), RedisError::NotFound) => None,
+ Err(err) => {
+ router_env::logger::warn!(
+ ?err,
+ redis_key,
+ type_name,
+ "Failed to read the cached value; rebuilding it"
+ );
+ None
+ }
+ }
+}
+
+/// Caches `value` in Redis under `redis_key` for `ttl_seconds`.
+///
+/// Never fatal: a write failure only means later calls rebuild the value, so it is logged and
+/// otherwise ignored.
+pub async fn cache_value_with_expiry<T>(
+ state: &SessionState,
+ redis_key: &str,
+ type_name: &'static str,
+ value: &T,
+ ttl_seconds: i64,
+) where
+ T: serde::Serialize + std::fmt::Debug,
+{
+ let stored: CustomResult<(), RedisError> = async {
+ state
+ .store
+ .get_redis_conn()?
+ .serialize_and_set_key_with_expiry(&redis_key.into(), value, ttl_seconds)
+ .await
+ }
+ .await;
+
+ match stored {
+ Ok(()) => router_env::logger::info!(redis_key, type_name, ttl_seconds, "Cached the value"),
+ Err(err) => router_env::logger::warn!(
+ ?err,
+ redis_key,
+ type_name,
+ "Failed to cache the value; later calls will rebuild it"
+ ),
+ }
+}
+
+/// Pins `candidate` under `redis_key` and returns whichever value is pinned there.
+///
+/// The first writer wins: its value is stored and returned, and every later caller — including
+/// one racing it right now — gets that value back instead of its own. This is what makes a value
+/// that is freshly generated on each build stable across concurrent calls without a lock.
+///
+/// Never fatal: if Redis cannot be reached the caller falls back to its own candidate, which is
+/// what it would have used had the pin not existed.
+pub async fn pin_value(
+ state: &SessionState,
+ redis_key: &str,
+ type_name: &'static str,
+ candidate: String,
+ ttl_seconds: i64,
+) -> String {
+ let pinned: CustomResult<Option<String>, RedisError> = async {
+ let redis = state.store.get_redis_conn()?;
+ match redis
+ .serialize_and_set_key_if_not_exist(&redis_key.into(), &candidate, Some(ttl_seconds))
+ .await?
+ {
+ redis_interface::SetnxReply::KeySet => Ok(None),
+ redis_interface::SetnxReply::KeyNotSet => redis
+ .get_and_deserialize_key::<String>(&redis_key.into(), type_name)
+ .await
+ .map(Some),
+ }
+ }
+ .await;
+
+ match pinned {
+ Ok(None) => candidate,
+ Ok(Some(existing)) => {
+ router_env::logger::debug!(redis_key, type_name, "Reusing the pinned value");
+ existing
+ }
+ Err(err) => {
+ router_env::logger::warn!(
+ ?err,
+ redis_key,
+ type_name,
+ "Failed to pin the value; using the freshly generated one"
+ );
+ candidate
+ }
+ }
+}