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
refactor(router): centralize accounts queries and duplicate-read tracking (#15227)
Hrithikesh43f09714ec67
diff --git a/Cargo.lock b/Cargo.lockindex e1c5634074..4ab6756996 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8127,11 +8127,13 @@ dependencies = [name = "router_derive"version = "0.1.0"dependencies = [+ "async-trait","common_utils","error-stack 0.4.1","indexmap 2.9.0","proc-macro2","quote",+ "router_env","serde","serde_json","strum 0.26.3",@@ -8582,6 +8584,7 @@ dependencies = ["num_cpus","rand 0.8.6","redis_interface",+ "router_derive","router_env","serde","serde_json",diff --git a/crates/common_utils/src/read_ledger.rs b/crates/common_utils/src/read_ledger.rsindex 21c12e6d3f..c5f9005d6c 100644--- a/crates/common_utils/src/read_ledger.rs+++ b/crates/common_utils/src/read_ledger.rs@@ -4,7 +4,7 @@//! statement including bind values, so different parameters stay distinct.use std::{- collections::HashMap,+ collections::{BTreeMap, HashMap},panic::Location,sync::{Arc, Mutex},};@@ -31,6 +31,38 @@ impl ReadStore {}}+/// Single reads are promoted into `duplicates` on their second occurrence.+/// Both collections share a lock so concurrent reads and snapshots stay consistent.+#[derive(Debug, Default)]+struct ReadLedgerState {+ single_reads: HashMap<String, Option<Location<'static>>>,+ duplicates: BTreeMap<String, Vec<Option<Location<'static>>>>,+}++impl ReadLedgerState {+ fn record_read(&mut self, statement: &str, location: Option<Location<'static>>) -> bool {+ if let Some(locations) = self.duplicates.get_mut(statement) {+ locations.push(location);+ true+ } else if let Some((statement, first_location)) = self.single_reads.remove_entry(statement)+ {+ self.duplicates+ .insert(statement, vec![first_location, location]);+ true+ } else {+ self.single_reads.insert(statement.to_owned(), location);+ false+ }+ }++ fn duplicate_reads(&self) -> Vec<(String, Vec<Option<Location<'static>>>)> {+ self.duplicates+ .iter()+ .map(|(statement, locations)| (statement.clone(), locations.clone()))+ .collect()+ }+}+/// Statements already read in an API session, shared across its stores.#[derive(Debug, Clone)]pub struct ReadLedger {@@ -38,7 +70,7 @@ pub struct ReadLedger {store: ReadStore,// Keep complete statements rather than fingerprints to avoid treating hash// collisions as duplicate reads. Bind values are never emitted as metrics.- reads: Arc<Mutex<HashMap<String, Vec<Option<Location<'static>>>>>>,+ state: Arc<Mutex<ReadLedgerState>>,}impl ReadLedger {@@ -47,7 +79,7 @@ impl ReadLedger {Self {flow,store: ReadStore::Main,- reads: Arc::new(Mutex::new(HashMap::new())),+ state: Arc::new(Mutex::new(ReadLedgerState::default())),}}@@ -70,154 +102,23 @@ impl ReadLedger {}/// Record a read with its optional captured origin, returning whether the session- /// already read the same SQL with the same bind values. Every read appends- /// its location, while only the first read allocates a stored SQL key.+ /// already read the same SQL with the same bind values. A second read promotes+ /// the statement into the duplicate collection; later reads append their origins.pub fn record_read(&self, statement: &str, location: Option<Location<'static>>) -> bool {- let mut reads = self- .reads+ self.state.lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- if let Some(locations) = reads.get_mut(statement) {- locations.push(location);- true- } else {- reads.insert(statement.to_owned(), vec![location]);- false- }+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .record_read(statement, location)}- /// Return statements read more than once, with locations in recording order.+ /// Snapshot duplicate statements in SQL order, with locations in recording order.pub fn duplicate_reads(&self) -> Vec<(String, Vec<Option<Location<'static>>>)> {- let reads = self- .reads+ self.state.lock()- .unwrap_or_else(std::sync::PoisonError::into_inner);- let mut duplicates = reads- .iter()- .filter(|(_, locations)| locations.len() > 1)- .map(|(statement, locations)| (statement.clone(), locations.clone()))- .collect::<Vec<_>>();- duplicates.sort_unstable_by(|(left, _), (right, _)| left.cmp(right));- duplicates+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .duplicate_reads()}}#[cfg(test)]-mod tests {- use super::*;-- const PI: &str = "SELECT .. FROM payment_intent WHERE payment_id = $1 -- binds: [pay_1]";- const OTHER: &str = "SELECT .. FROM payment_intent WHERE payment_id = $1 -- binds: [pay_2]";-- #[track_caller]- fn record_read(ledger: &ReadLedger, statement: &str) -> bool {- ledger.record_read(statement, Some(*Location::caller()))- }-- #[test]- fn only_reads_after_the_first_are_duplicates() {- let ledger = ReadLedger::new("PaymentsConfirm".to_owned());- assert!(!record_read(&ledger, PI));- for _ in 0..20 {- assert!(record_read(&ledger, PI));- }- }-- #[test]- fn records_every_location_for_a_statement_in_order() {- let ledger = ReadLedger::new("PaymentsConfirm".to_owned());- let first = *Location::caller();- let second = *Location::caller();-- assert!(!ledger.record_read(PI, Some(first)));- assert!(ledger.duplicate_reads().is_empty());- assert!(!ledger.record_read(OTHER, Some(first)));- assert!(ledger.record_read(PI, Some(second)));- assert!(ledger.record_read(PI, None));-- let reads = ledger.reads.lock().expect("read ledger lock");- assert_eq!(reads.get(PI), Some(&vec![Some(first), Some(second), None]));- drop(reads);- assert_eq!(- ledger.duplicate_reads(),- vec![(PI.to_owned(), vec![Some(first), Some(second), None])]- );- }-- #[test]- fn different_binds_are_different_records() {- let ledger = ReadLedger::new("PaymentsConfirm".to_owned());- assert!(!record_read(&ledger, PI));- assert!(!record_read(&ledger, OTHER));- assert!(record_read(&ledger, OTHER));- assert!(record_read(&ledger, PI));- }-- #[test]- fn sessions_do_not_share_reads() {- let first = ReadLedger::new("PaymentsConfirm".to_owned());- let second = ReadLedger::new("PaymentsConfirm".to_owned());- assert!(!record_read(&first, PI));- assert!(!record_read(&second, PI));- }-- #[test]- fn store_labels_share_reads_and_preserve_the_session_flow() {- let main = ReadLedger::new("PaymentsConfirm".to_owned());- let accounts = main.for_store(ReadStore::Accounts);- let global = main.for_store(ReadStore::Global);-- assert_eq!(main.store().as_str(), "main");- assert_eq!(accounts.store().as_str(), "accounts");- assert_eq!(global.store().as_str(), "global");- for ledger in [&main, &accounts, &global] {- assert_eq!(ledger.flow(), "PaymentsConfirm");- }-- assert!(!record_read(&main, PI));- assert!(record_read(&accounts, PI));- assert!(record_read(&global, PI));- assert!(!record_read(&accounts, OTHER));- assert!(record_read(&main, OTHER));- }-- #[test]- fn different_statements_are_different_reads() {- let ledger = ReadLedger::new("PaymentsConfirm".to_owned());- assert!(!record_read(&ledger, "SELECT 1908"));- assert!(!record_read(&ledger, "SELECT 3600"));- assert!(record_read(&ledger, "SELECT 1908"));- assert!(record_read(&ledger, "SELECT 3600"));- }-- #[test]- fn distinct_statements_are_all_tracked() {- let ledger = ReadLedger::new("PaymentsConfirm".to_owned());- for index in 0..5_000 {- assert!(!record_read(&ledger, &format!("SELECT {index}")));- }- assert!(record_read(&ledger, "SELECT 0"));- assert!(record_read(&ledger, "SELECT 4999"));- }-- #[test]- fn shared_ledger_counts_each_concurrent_repeat_once() {- let ledger = Arc::new(ReadLedger::new("PaymentsConfirm".to_owned()));- let barrier = Arc::new(std::sync::Barrier::new(8));- let threads = (0..8)- .map(|_| {- let ledger = Arc::clone(&ledger);- let barrier = Arc::clone(&barrier);- std::thread::spawn(move || {- barrier.wait();- record_read(&ledger, PI)- })- })- .collect::<Vec<_>>();- let repeats = threads- .into_iter()- .map(|thread| usize::from(thread.join().expect("read thread")))- .sum::<usize>();- assert_eq!(repeats, 7);- }-}+mod test;diff --git a/crates/common_utils/src/read_ledger/test.rs b/crates/common_utils/src/read_ledger/test.rsnew file mode 100644index 0000000000..2346152fb0--- /dev/null+++ b/crates/common_utils/src/read_ledger/test.rs@@ -0,0 +1,143 @@+use super::*;++const PI: &str = "SELECT .. FROM payment_intent WHERE payment_id = $1 -- binds: [pay_1]";+const OTHER: &str = "SELECT .. FROM payment_intent WHERE payment_id = $1 -- binds: [pay_2]";++#[track_caller]+fn record_read(ledger: &ReadLedger, statement: &str) -> bool {+ ledger.record_read(statement, Some(*Location::caller()))+}++#[test]+fn only_reads_after_the_first_are_duplicates() {+ let ledger = ReadLedger::new("PaymentsConfirm".to_owned());+ assert!(!record_read(&ledger, PI));+ for _ in 0..20 {+ assert!(record_read(&ledger, PI));+ }+}++#[test]+fn records_every_location_for_a_statement_in_order() {+ let ledger = ReadLedger::new("PaymentsConfirm".to_owned());+ let first = *Location::caller();+ let second = *Location::caller();++ assert!(!ledger.record_read(PI, Some(first)));+ assert!(ledger.duplicate_reads().is_empty());+ assert!(!ledger.record_read(OTHER, Some(first)));+ assert!(ledger.record_read(PI, Some(second)));+ assert!(ledger.record_read(PI, None));++ assert_eq!(+ ledger.duplicate_reads(),+ vec![(PI.to_owned(), vec![Some(first), Some(second), None])]+ );+}++#[test]+fn duplicate_snapshots_are_sorted_and_independent() {+ let ledger = ReadLedger::new("PaymentsConfirm".to_owned());+ assert!(!ledger.record_read(OTHER, None));+ assert!(ledger.record_read(OTHER, None));+ let snapshot = ledger.duplicate_reads();++ assert!(!ledger.record_read(PI, None));+ assert!(ledger.record_read(PI, None));+ assert!(ledger.record_read(OTHER, None));+ assert!(!ledger.record_read("SELECT 1", None));++ assert_eq!(snapshot, vec![(OTHER.to_owned(), vec![None, None])]);+ assert_eq!(+ ledger.duplicate_reads(),+ vec![+ (PI.to_owned(), vec![None, None]),+ (OTHER.to_owned(), vec![None, None, None]),+ ]+ );+}++#[test]+fn different_binds_are_different_records() {+ let ledger = ReadLedger::new("PaymentsConfirm".to_owned());+ assert!(!record_read(&ledger, PI));+ assert!(!record_read(&ledger, OTHER));+ assert!(record_read(&ledger, OTHER));+ assert!(record_read(&ledger, PI));+}++#[test]+fn sessions_do_not_share_reads() {+ let first = ReadLedger::new("PaymentsConfirm".to_owned());+ let second = ReadLedger::new("PaymentsConfirm".to_owned());+ assert!(!record_read(&first, PI));+ assert!(!record_read(&second, PI));+}++#[test]+fn store_labels_share_reads_and_preserve_the_session_flow() {+ let main = ReadLedger::new("PaymentsConfirm".to_owned());+ let accounts = main.for_store(ReadStore::Accounts);+ let global = main.for_store(ReadStore::Global);++ assert_eq!(main.store().as_str(), "main");+ assert_eq!(accounts.store().as_str(), "accounts");+ assert_eq!(global.store().as_str(), "global");+ for ledger in [&main, &accounts, &global] {+ assert_eq!(ledger.flow(), "PaymentsConfirm");+ }++ assert!(!record_read(&main, PI));+ assert!(record_read(&accounts, PI));+ assert!(record_read(&global, PI));+ assert!(!record_read(&accounts, OTHER));+ assert!(record_read(&main, OTHER));+ assert_eq!(main.duplicate_reads(), accounts.duplicate_reads());+ assert_eq!(main.duplicate_reads(), global.duplicate_reads());+ assert_eq!(main.duplicate_reads().len(), 2);+}++#[test]+fn different_statements_are_different_reads() {+ let ledger = ReadLedger::new("PaymentsConfirm".to_owned());+ assert!(!record_read(&ledger, "SELECT 1908"));+ assert!(!record_read(&ledger, "SELECT 3600"));+ assert!(record_read(&ledger, "SELECT 1908"));+ assert!(record_read(&ledger, "SELECT 3600"));+}++#[test]+fn distinct_statements_are_all_tracked() {+ let ledger = ReadLedger::new("PaymentsConfirm".to_owned());+ for index in 0..5_000 {+ assert!(!record_read(&ledger, &format!("SELECT {index}")));+ }+ assert!(record_read(&ledger, "SELECT 0"));+ assert!(record_read(&ledger, "SELECT 4999"));+}++#[test]+fn shared_ledger_counts_each_concurrent_repeat_once() {+ let ledger = Arc::new(ReadLedger::new("PaymentsConfirm".to_owned()));+ let barrier = Arc::new(std::sync::Barrier::new(8));+ let threads = (0..8)+ .map(|_| {+ let ledger = Arc::clone(&ledger);+ let barrier = Arc::clone(&barrier);+ std::thread::spawn(move || {+ barrier.wait();+ record_read(&ledger, PI)+ })+ })+ .collect::<Vec<_>>();+ let repeats = threads+ .into_iter()+ .map(|thread| usize::from(thread.join().expect("read thread")))+ .sum::<usize>();+ assert_eq!(repeats, 7);+ let duplicates = ledger.duplicate_reads();+ assert_eq!(duplicates.len(), 1);+ let (statement, locations) = duplicates.first().expect("duplicate read");+ assert_eq!(statement, PI);+ assert_eq!(locations.len(), 8);+}diff --git a/crates/hyperswitch_domain_models/src/authentication.rs b/crates/hyperswitch_domain_models/src/authentication.rsindex dbfa6a2c89..0102047255 100644--- a/crates/hyperswitch_domain_models/src/authentication.rs+++ b/crates/hyperswitch_domain_models/src/authentication.rs@@ -766,6 +766,7 @@ impl From<AuthenticationUpdate> for diesel_models::authentication::Authenticatio}}+#[router_derive::track_async_interface]#[async_trait]pub trait AuthenticationInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/business_profile.rs b/crates/hyperswitch_domain_models/src/business_profile.rsindex 3ed45cebd8..a7f96e7479 100644--- a/crates/hyperswitch_domain_models/src/business_profile.rs+++ b/crates/hyperswitch_domain_models/src/business_profile.rs@@ -1374,6 +1374,7 @@ pub enum ProfileUpdate {},}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait ProfileInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/card_issuer.rs b/crates/hyperswitch_domain_models/src/card_issuer.rsindex 57ae6581dd..77a5cb7d4f 100644--- a/crates/hyperswitch_domain_models/src/card_issuer.rs+++ b/crates/hyperswitch_domain_models/src/card_issuer.rs@@ -1,6 +1,7 @@use common_utils::{errors, id_type};use diesel_models::card_issuer;+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait CardIssuersInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/cards_info.rs b/crates/hyperswitch_domain_models/src/cards_info.rsindex 6fe3b081c2..b5857a433c 100644--- a/crates/hyperswitch_domain_models/src/cards_info.rs+++ b/crates/hyperswitch_domain_models/src/cards_info.rs@@ -1,6 +1,7 @@use common_utils::errors;use diesel_models::cards_info;+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait CardsInfoInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/configs.rs b/crates/hyperswitch_domain_models/src/configs.rsindex 53811f6101..4d251920f7 100644--- a/crates/hyperswitch_domain_models/src/configs.rs+++ b/crates/hyperswitch_domain_models/src/configs.rs@@ -5,6 +5,7 @@ use diesel_models::configs as storage;/// reads are served from (and populate) the config cache, and writes redact the/// cached entry across all instances. Direct database access is intentionally/// not exposed here.+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait ConfigInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rsindex 5114373f5f..e3c854e0d2 100644--- a/crates/hyperswitch_domain_models/src/customer.rs+++ b/crates/hyperswitch_domain_models/src/customer.rs@@ -315,6 +315,7 @@ impl From<CustomerListConstraints> for query::CustomerListConstraints {}}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait CustomerInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/hierarchical_resource.rs b/crates/hyperswitch_domain_models/src/hierarchical_resource.rsindex ba61fcb86a..ddd0b827db 100644--- a/crates/hyperswitch_domain_models/src/hierarchical_resource.rs+++ b/crates/hyperswitch_domain_models/src/hierarchical_resource.rs@@ -137,6 +137,7 @@ impl From<HierarchicalResourceDataUpdate>}}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait HierarchicalResourceInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/invoice.rs b/crates/hyperswitch_domain_models/src/invoice.rsindex 65d4cd007c..6990e93171 100644--- a/crates/hyperswitch_domain_models/src/invoice.rs+++ b/crates/hyperswitch_domain_models/src/invoice.rs@@ -140,6 +140,7 @@ impl Invoice {}}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait InvoiceInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/merchant_account.rs b/crates/hyperswitch_domain_models/src/merchant_account.rsindex e2ff6aa052..ca8cf40295 100644--- a/crates/hyperswitch_domain_models/src/merchant_account.rs+++ b/crates/hyperswitch_domain_models/src/merchant_account.rs@@ -364,6 +364,7 @@ impl MerchantAccount {}}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait MerchantAccountInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs b/crates/hyperswitch_domain_models/src/merchant_connector_account.rsindex 5c263bc8ef..caf4a13a2e 100644--- a/crates/hyperswitch_domain_models/src/merchant_connector_account.rs+++ b/crates/hyperswitch_domain_models/src/merchant_connector_account.rs@@ -897,6 +897,7 @@ impl From<DieselMerchantConnectorAccountFeatureMetadata>}}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait MerchantConnectorAccountInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/merchant_key_store.rs b/crates/hyperswitch_domain_models/src/merchant_key_store.rsindex df8d0ef056..d124b9c79a 100644--- a/crates/hyperswitch_domain_models/src/merchant_key_store.rs+++ b/crates/hyperswitch_domain_models/src/merchant_key_store.rs@@ -75,6 +75,7 @@ impl super::behaviour::Conversion for MerchantKeyStore {}}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait MerchantKeyStoreInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/payment_methods.rs b/crates/hyperswitch_domain_models/src/payment_methods.rsindex d0f8fcd0b5..e423bcc3bf 100644--- a/crates/hyperswitch_domain_models/src/payment_methods.rs+++ b/crates/hyperswitch_domain_models/src/payment_methods.rs@@ -517,6 +517,7 @@ pub struct PaymentMethodWithRawData {pub vault_payment_method_token_data: Option<VaultPaymentMethodData>,}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait PaymentMethodInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rsindex 61d895919f..74feb1bf5b 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_attempt.rs@@ -66,6 +66,7 @@ use crate::{router_request_types,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait PaymentAttemptInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs b/crates/hyperswitch_domain_models/src/payments/payment_intent.rsindex 35c32fa731..7472a84174 100644--- a/crates/hyperswitch_domain_models/src/payments/payment_intent.rs+++ b/crates/hyperswitch_domain_models/src/payments/payment_intent.rs@@ -44,6 +44,7 @@ use crate::{#[cfg(feature = "v1")]use crate::{errors, RemoteStorageObject};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait PaymentIntentInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rsindex aa343ce991..c123930d87 100644--- a/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs+++ b/crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs@@ -10,6 +10,7 @@ use time::PrimitiveDateTime;use super::payouts::Payouts;+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait PayoutAttemptInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/payouts/payouts.rs b/crates/hyperswitch_domain_models/src/payouts/payouts.rsindex e3ae828fd2..bd5d6bcb15 100644--- a/crates/hyperswitch_domain_models/src/payouts/payouts.rs+++ b/crates/hyperswitch_domain_models/src/payouts/payouts.rs@@ -10,6 +10,7 @@ use super::payout_attempt::PayoutAttempt;use super::PayoutFetchConstraints;use crate::{merchant_key_store::MerchantKeyStore, type_encryption::OptionalEncryptableJsonType};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait PayoutsInterface {type Error;diff --git a/crates/hyperswitch_domain_models/src/subscription.rs b/crates/hyperswitch_domain_models/src/subscription.rsindex a58c267b2e..3ec619cfdb 100644--- a/crates/hyperswitch_domain_models/src/subscription.rs+++ b/crates/hyperswitch_domain_models/src/subscription.rs@@ -191,6 +191,7 @@ impl super::behaviour::Conversion for Subscription {}}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait SubscriptionInterface {type Error;diff --git a/crates/router/src/analytics.rs b/crates/router/src/analytics.rsindex 63ae835d7c..bf92bbfc0d 100644--- a/crates/router/src/analytics.rs+++ b/crates/router/src/analytics.rs@@ -1998,9 +1998,7 @@ pub mod routes {payload: &ReportRequest,) -> Result<Option<String>, error_stack::Report<AnalyticsError>> {match payload.return_url {- Some(_) => {- get_payment_response_hash_key(state.store.as_ref(), key_store, auth_info).await- }+ Some(_) => get_payment_response_hash_key(state, key_store, auth_info).await,None => Ok(None),}}diff --git a/crates/router/src/connection.rs b/crates/router/src/connection.rsindex 947690937f..82e32d641a 100644--- a/crates/router/src/connection.rs+++ b/crates/router/src/connection.rs@@ -70,42 +70,6 @@ pub async fn pg_connection_read<'a, T: DatabaseStore + RequestContext>())}-pub async fn pg_accounts_connection_read<'a, T: DatabaseStore + RequestContext>(- store: &'a T,-) -> errors::CustomResult<DatabaseConnectionWithContext<'a>, storage_errors::StorageError> {- // If only OLAP is enabled get replica pool.- #[cfg(all(feature = "olap", not(feature = "oltp")))]- let pool = store.get_accounts_replica_pool();-- // If either one of these are true we need to get master pool.- // 1. Only OLTP is enabled.- // 2. Both OLAP and OLTP is enabled.- // 3. Both OLAP and OLTP is disabled.- #[cfg(any(- all(not(feature = "olap"), feature = "oltp"),- all(feature = "olap", feature = "oltp"),- all(not(feature = "olap"), not(feature = "oltp"))- ))]- let pool = store.get_accounts_master_pool();-- #[cfg_attr(not(feature = "deja"), allow(unused_mut))]- let mut connection = pool- .pg_pool- .get()- .await- .change_context(storage_errors::StorageError::DatabaseConnectionError)?;-- #[cfg(feature = "deja")]- deja_route_replay_schema(&mut connection, store).await;-- Ok(DatabaseConnectionWithContext::new(- connection,- store.request_id().map(str::to_owned),- pool.event_emitter.clone(),- store.read_ledger().cloned(),- ))-}-pub async fn pg_connection_write<'a, T: DatabaseStore + RequestContext>(store: &'a T,) -> errors::CustomResult<DatabaseConnectionWithContext<'a>, storage_errors::StorageError> {@@ -129,27 +93,3 @@ pub async fn pg_connection_write<'a, T: DatabaseStore + RequestContext>(store.read_ledger().cloned(),))}--pub async fn pg_accounts_connection_write<'a, T: DatabaseStore + RequestContext>(- store: &'a T,-) -> errors::CustomResult<DatabaseConnectionWithContext<'a>, storage_errors::StorageError> {- // Since all writes should happen to master DB only choose master DB.- let pool = store.get_accounts_master_pool();-- #[cfg_attr(not(feature = "deja"), allow(unused_mut))]- let mut connection = pool- .pg_pool- .get()- .await- .change_context(storage_errors::StorageError::DatabaseConnectionError)?;-- #[cfg(feature = "deja")]- deja_route_replay_schema(&mut connection, store).await;-- Ok(DatabaseConnectionWithContext::new(- connection,- store.request_id().map(str::to_owned),- pool.event_emitter.clone(),- store.read_ledger().cloned(),- ))-}diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex d43b7a0534..9675eaa80b 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -43,7 +43,7 @@ use crate::{pm_auth::helpers::PaymentAuthConnectorDataExt,routing, utils as core_utils,},- db::{AccountsStorageInterface, StorageInterface},+ db::AccountsStorageInterface,logger,routes::{app::SessionStateInfo, metrics, SessionState},services::{@@ -123,7 +123,8 @@ pub async fn create_organization() -> RouterResponse<api::OrganizationResponse> {let db_organization = ForeignFrom::foreign_from(req);state- .track_accounts_query(|db| db.insert_organization(db_organization))+ .accounts_store+ .insert_organization(db_organization).await.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {message: "Organization with the given organization_name already exists".to_string(),@@ -145,9 +146,8 @@ pub async fn update_organization(metadata: req.metadata,};state- .track_accounts_query(|db| {- db.update_organization_by_org_id(&org_id.organization_id, organization_update)- })+ .accounts_store+ .update_organization_by_org_id(&org_id.organization_id, organization_update).await.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {message: "organization with the given id does not exist".to_string(),@@ -167,24 +167,16 @@ pub async fn get_organization() -> RouterResponse<api::OrganizationResponse> {#[cfg(all(feature = "v1", feature = "olap"))]{- state- .track_accounts_query(|db| async move {- CreateOrValidateOrganization::new(Some(org_id.organization_id), None)- .create_or_validate(db)- .await- })+ CreateOrValidateOrganization::new(Some(org_id.organization_id), None)+ .create_or_validate(state.accounts_store.as_ref()).await.map(ForeignFrom::foreign_from).map(service_api::ApplicationResponse::Json)}#[cfg(all(feature = "v2", feature = "olap"))]{- state- .track_accounts_query(|db| async move {- CreateOrValidateOrganization::new(org_id.organization_id)- .create_or_validate(db)- .await- })+ CreateOrValidateOrganization::new(org_id.organization_id)+ .create_or_validate(state.accounts_store.as_ref()).await.map(ForeignFrom::foreign_from).map(service_api::ApplicationResponse::Json)@@ -238,7 +230,8 @@ pub async fn convert_organization_to_platform_organization(})?;let organization = state- .track_accounts_query(|db| db.find_organization_by_org_id(&org_id.organization_id))+ .accounts_store+ .find_organization_by_org_id(&org_id.organization_id).await.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {message: "Organization with the given id does not exist".to_string(),@@ -263,12 +256,11 @@ pub async fn convert_organization_to_platform_organization(})?;state- .track_accounts_query(|db| {- db.update_organization_by_org_id(- &org_id.organization_id,- diesel_models::organization::OrganizationUpdate::ConvertToPlatform,- )- })+ .accounts_store+ .update_organization_by_org_id(+ &org_id.organization_id,+ diesel_models::organization::OrganizationUpdate::ConvertToPlatform,+ ).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to update organization type to Platform")?;@@ -305,14 +297,13 @@ pub async fn convert_organization_to_platform_organization(.await?;let updated_organization = state- .track_accounts_query(|db| {- db.update_organization_by_org_id(- &org_id.organization_id,- diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {- platform_merchant_id: platform_merchant_id.clone(),- },- )- })+ .accounts_store+ .update_organization_by_org_id(+ &org_id.organization_id,+ diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {+ platform_merchant_id: platform_merchant_id.clone(),+ },+ ).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to update organization type to Platform")?;@@ -386,25 +377,28 @@ pub async fn create_merchant_account().await?;- db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into())+ let key_store_master_key = master_key.to_vec().into();+ state+ .accounts_store+ .insert_merchant_key_store(key_store.clone(), &key_store_master_key).await.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.insert_merchant(domain_merchant_account, &key_store).await.to_duplicate_response(errors::ApiErrorResponse::DuplicateMerchantAccount)?;if merchant_account.is_platform_account() {state- .track_accounts_query(|db| {- db.update_organization_by_org_id(- &merchant_account.organization_id,- diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {- platform_merchant_id: merchant_id.clone(),- },- )- })+ .accounts_store+ .update_organization_by_org_id(+ &merchant_account.organization_id,+ diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {+ platform_merchant_id: merchant_id.clone(),+ },+ ).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to update organization with platform_merchant_id")?;@@ -528,12 +522,8 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {};let requested_account_type = self.merchant_account_type;- let organization = state- .track_accounts_query(|db| async move {- CreateOrValidateOrganization::new(org_id, requested_account_type)- .create_or_validate(db)- .await- })+ let organization = CreateOrValidateOrganization::new(org_id, requested_account_type)+ .create_or_validate(state.accounts_store.as_ref()).await?;let merchant_account_type = match organization.get_organization_type() {@@ -924,12 +914,8 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {)?;let organization_id = self.organization_id.clone();- let organization = state- .track_accounts_query(|db| async move {- CreateOrValidateOrganization::new(organization_id)- .create_or_validate(db)- .await- })+ let organization = CreateOrValidateOrganization::new(organization_id)+ .create_or_validate(state.accounts_store.as_ref()).await?;// V2 currently supports creation of Standard merchant accounts only, irrespective of organization type@@ -1001,7 +987,7 @@ pub async fn list_merchant_account(organization_id: api_models::organization::OrganizationId,) -> RouterResponse<Vec<api::MerchantAccountResponse>> {let merchant_accounts = state- .store+ .accounts_store.list_merchant_accounts_by_organization_id(&organization_id.organization_id).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -1035,7 +1021,7 @@ pub async fn list_merchant_account(}}let merchant_accounts = state- .store+ .accounts_store.list_merchant_accounts_by_organization_id(&req.organization_id).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -1060,15 +1046,15 @@ pub async fn get_merchant_account(_profile_id: Option<id_type::ProfileId>,) -> RouterResponse<api::MerchantAccountResponse> {let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(- &req.merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&req.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&req.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -1085,12 +1071,12 @@ pub async fn get_merchant_account(/// primary_business_details, create a profilepub async fn create_profile_from_business_labels(state: &SessionState,- db: &dyn StorageInterface,key_store: &domain::MerchantKeyStore,merchant_id: &id_type::MerchantId,new_business_details: Vec<admin_types::PrimaryBusinessDetails>,) -> RouterResult<()> {- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -1133,7 +1119,9 @@ pub async fn create_profile_from_business_labels(// If a profile is created, then unset the default profileif profile_create_result.is_ok() && merchant_account.default_profile.is_some() {let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile;- db.update_merchant(merchant_account.clone(), unset_default_profile, key_store)+ state+ .accounts_store+ .update_merchant(merchant_account.clone(), unset_default_profile, key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;}@@ -1165,7 +1153,6 @@ impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {let key_manager_state = &state.into();let key = key_store.key.get_inner().peek();- let db = state.store.as_ref();let primary_business_details = self.get_primary_details_as_value().change_context(errors::ApiErrorResponse::InvalidDataValue {field_name: "primary_business_details".into(),@@ -1218,7 +1205,8 @@ impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {// This supports changing the business profile by passing in the profile_idlet business_profile_id_update = if let Some(ref profile_id) = self.default_profile {- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -1233,7 +1221,7 @@ impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {// Validate whether profile_id passed in request is valid and is linked to the merchantcore_utils::validate_and_get_business_profile(- state.store.as_ref(),+ state.accounts_store.as_ref(),platform.get_processor(),Some(profile_id),)@@ -1251,7 +1239,6 @@ impl MerchantAccountUpdateBridge for api::MerchantAccountUpdate {.async_map(|primary_business_details| async {let _ = Box::pin(create_profile_from_business_labels(state,- db,key_store,merchant_id,primary_business_details,@@ -1415,8 +1402,10 @@ pub async fn merchant_account_update(req: api::MerchantAccountUpdate,) -> RouterResponse<api::MerchantAccountResponse> {let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into())+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -1425,7 +1414,8 @@ pub async fn merchant_account_update(.await.attach_printable("Failed to create merchant account update object")?;- let response = db+ let response = state+ .accounts_store.update_specific_fields_in_merchant(merchant_id,merchant_account_storage_object,@@ -1447,15 +1437,15 @@ pub async fn merchant_account_delete() -> RouterResponse<api::MerchantAccountDeleteResponse> {let mut is_deleted = false;let db = state.store.as_ref();- let merchant_key_store = db- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store.get_master_key().to_vec().into();+ let merchant_key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &merchant_key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -1466,12 +1456,14 @@ pub async fn merchant_account_delete(}))})?;- let is_merchant_account_deleted = db+ let is_merchant_account_deleted = state+ .accounts_store.delete_merchant_account_by_merchant_id(&merchant_id).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;if is_merchant_account_deleted {- let is_merchant_key_store_deleted = db+ let is_merchant_key_store_deleted = state+ .accounts_store.delete_merchant_key_store_by_merchant_id(&merchant_id).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -1550,8 +1542,9 @@ async fn validate_merchant_id(merchant_id: &id_type::MerchantId,key_store: &domain::MerchantKeyStore,) -> RouterResult<domain::MerchantAccount> {- let db = &*state.store;- db.find_merchant_account_by_merchant_id(merchant_id, key_store)+ state+ .accounts_store+ .find_merchant_account_by_merchant_id(merchant_id, key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)}@@ -1632,7 +1625,7 @@ impl ConnectorMetadata<'_> {struct PMAuthConfigValidation<'a> {connector_type: &'a api_enums::ConnectorType,pm_auth_config: &'a Option<pii::SecretSerdeValue>,- db: &'a dyn StorageInterface,+ state: &'a SessionState,merchant_id: &'a id_type::MerchantId,profile_id: &'a id_type::ProfileId,}@@ -1649,12 +1642,10 @@ impl PMAuthConfigValidation<'_> {// Fetching disabled MCAs too: PM auth config may reference MCAs that are// temporarily disabled — validation checks existence, not activity.- let all_mcas = self- .db- .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(- self.merchant_id,- self.profile_id,- )+ let all_mcas = self.state.accounts_store.list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ self.merchant_id,+ self.profile_id,+ ).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: self.merchant_id.get_string_repr().to_owned(),@@ -1765,7 +1756,7 @@ impl ConnectorTypeAndConnectorName<'_> {struct MerchantDefaultConfigUpdate<'a> {routable_connector: &'a Option<api_enums::RoutableConnectors>,merchant_connector_id: &'a id_type::MerchantConnectorAccountId,- store: &'a dyn StorageInterface,+ state: &'a SessionState,merchant_id: &'a id_type::MerchantId,profile_id: &'a id_type::ProfileId,transaction_type: &'a api_enums::TransactionType,@@ -1778,14 +1769,14 @@ impl MerchantDefaultConfigUpdate<'_> {&self,) -> RouterResult<()> {let mut default_routing_config = routing::helpers::get_merchant_default_config(- self.store,+ self.state.store.as_ref(),self.merchant_id.get_string_repr(),self.transaction_type,).await?;let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config(- self.store,+ self.state.store.as_ref(),self.profile_id.get_string_repr(),self.transaction_type,)@@ -1800,7 +1791,7 @@ impl MerchantDefaultConfigUpdate<'_> {if !default_routing_config.contains(&choice) {default_routing_config.push(choice.clone());routing::helpers::update_merchant_default_config(- self.store,+ self.state.store.as_ref(),self.merchant_id.get_string_repr(),default_routing_config.clone(),self.transaction_type,@@ -1810,7 +1801,7 @@ impl MerchantDefaultConfigUpdate<'_> {if !default_routing_config_for_profile.contains(&choice.clone()) {default_routing_config_for_profile.push(choice.clone());routing::helpers::update_merchant_default_config(- self.store,+ self.state.store.as_ref(),self.profile_id.get_string_repr(),default_routing_config_for_profile.clone(),self.transaction_type,@@ -1843,7 +1834,8 @@ impl MerchantDefaultConfigUpdate<'_> {let profile_update = domain::ProfileUpdate::DefaultRoutingFallbackUpdate {default_fallback_routing: Some(default_fallback_routing),};- self.store+ self.state+ .accounts_store.update_profile_by_profile_id(self.key_store,self.business_profile.clone(),@@ -1863,14 +1855,14 @@ impl MerchantDefaultConfigUpdate<'_> {&self,) -> RouterResult<()> {let mut default_routing_config = routing::helpers::get_merchant_default_config(- self.store,+ self.state.store.as_ref(),self.merchant_id.get_string_repr(),self.transaction_type,).await?;let mut default_routing_config_for_profile = routing::helpers::get_merchant_default_config(- self.store,+ self.state.store.as_ref(),self.profile_id.get_string_repr(),self.transaction_type,)@@ -1887,7 +1879,7 @@ impl MerchantDefaultConfigUpdate<'_> {mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id)});routing::helpers::update_merchant_default_config(- self.store,+ self.state.store.as_ref(),self.merchant_id.get_string_repr(),default_routing_config.clone(),self.transaction_type,@@ -1899,7 +1891,7 @@ impl MerchantDefaultConfigUpdate<'_> {mca.merchant_connector_id.as_ref() != Some(self.merchant_connector_id)});routing::helpers::update_merchant_default_config(- self.store,+ self.state.store.as_ref(),self.profile_id.get_string_repr(),default_routing_config_for_profile.clone(),self.transaction_type,@@ -1934,7 +1926,8 @@ impl MerchantDefaultConfigUpdate<'_> {let profile_update = domain::ProfileUpdate::DefaultRoutingFallbackUpdate {default_fallback_routing: Some(default_fallback_routing),};- self.store+ self.state+ .accounts_store.update_profile_by_profile_id(self.key_store,self.business_profile.clone(),@@ -1954,7 +1947,7 @@ impl MerchantDefaultConfigUpdate<'_> {struct DefaultFallbackRoutingConfigUpdate<'a> {routable_connector: &'a Option<api_enums::RoutableConnectors>,merchant_connector_id: &'a id_type::MerchantConnectorAccountId,- store: &'a dyn StorageInterface,+ state: &'a SessionState,business_profile: domain::Profile,key_store: hyperswitch_domain_models::merchant_key_store::MerchantKeyStore,key_manager_state: &'a KeyManagerState,@@ -1978,7 +1971,7 @@ impl DefaultFallbackRoutingConfigUpdate<'_> {profile_wrapper.update_default_fallback_routing_of_connectors_under_profile(- self.store,+ self.state.accounts_store.as_ref(),default_routing_config_for_profile,self.key_manager_state,&self.key_store,@@ -2008,7 +2001,7 @@ impl DefaultFallbackRoutingConfigUpdate<'_> {profile_wrapper.update_default_fallback_routing_of_connectors_under_profile(- self.store,+ self.state.accounts_store.as_ref(),default_routing_config_for_profile,self.key_manager_state,&self.key_store,@@ -2024,7 +2017,7 @@ impl DefaultFallbackRoutingConfigUpdate<'_> {trait MerchantConnectorAccountUpdateBridge {async fn get_merchant_connector_account_from_id(self,- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,merchant_id: &id_type::MerchantId,merchant_connector_id: &id_type::MerchantConnectorAccountId,key_store: &domain::MerchantKeyStore,@@ -2044,7 +2037,7 @@ trait MerchantConnectorAccountUpdateBridge {impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectorUpdate {async fn get_merchant_connector_account_from_id(self,- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,_merchant_id: &id_type::MerchantId,merchant_connector_id: &id_type::MerchantConnectorAccountId,key_store: &domain::MerchantKeyStore,@@ -2097,7 +2090,7 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectlet pm_auth_config_validation = PMAuthConfigValidation {connector_type: &self.connector_type,pm_auth_config: &self.pm_auth_config,- db: state.store.as_ref(),+ state,merchant_id: platform.get_processor().get_account().get_id(),profile_id: &mca.profile_id.clone(),};@@ -2200,7 +2193,7 @@ impl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectimpl MerchantConnectorAccountUpdateBridge for api_models::admin::MerchantConnectorUpdate {async fn get_merchant_connector_account_from_id(self,- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,merchant_id: &id_type::MerchantId,merchant_connector_id: &id_type::MerchantConnectorAccountId,key_store: &domain::MerchantKeyStore,@@ -2384,7 +2377,7 @@ trait MerchantConnectorAccountCreateBridge {async fn validate_and_get_business_profile(self,processor: &domain::Processor,- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,) -> RouterResult<domain::Profile>;}@@ -2529,7 +2522,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {async fn validate_and_get_business_profile(self,processor: &domain::Processor,- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,) -> RouterResult<domain::Profile> {let profile_id = self.profile_id;// Check whether this profile belongs to the merchant@@ -2734,7 +2727,7 @@ impl MerchantConnectorAccountCreateBridge for api::MerchantConnectorCreate {async fn validate_and_get_business_profile(self,processor: &domain::Processor,- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,) -> RouterResult<domain::Profile> {match self.profile_id@@ -2783,7 +2776,6 @@ pub async fn create_connector(processor: domain::Processor,auth_profile_id: Option<id_type::ProfileId>,) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {- let store = state.store.as_ref();let key_manager_state = &(&state).into();#[cfg(feature = "dummy_connector")]fp_utils::when(@@ -2835,7 +2827,7 @@ pub async fn create_connector(let business_profile = req.clone()- .validate_and_get_business_profile(&processor, store)+ .validate_and_get_business_profile(&processor, state.accounts_store.as_ref()).await?;core_utils::validate_profile_id_from_auth_layer(auth_profile_id, &business_profile)?;@@ -2844,7 +2836,7 @@ pub async fn create_connector(let profile_wrapper = ProfileWrapper::new(business_profile.clone());profile_wrapper.update_revenue_recovery_algorithm_under_profile(- store,+ state.accounts_store.as_ref(),key_manager_state,processor.get_key_store(),common_enums::RevenueRecoveryAlgorithmType::Monitoring,@@ -2855,7 +2847,7 @@ pub async fn create_connector(let pm_auth_config_validation = PMAuthConfigValidation {connector_type: &req.connector_type,pm_auth_config: &req.pm_auth_config,- db: store,+ state: &state,merchant_id,profile_id: business_profile.get_id(),};@@ -2870,7 +2862,7 @@ pub async fn create_connector(// The purpose of this merchant account update is just to update the// merchant account `modified_at` field for KGraph cache invalidationstate- .store+ .accounts_store.update_specific_fields_in_merchant(merchant_id,storage::MerchantAccountUpdate::ModifiedAtUpdate,@@ -2891,7 +2883,7 @@ pub async fn create_connector(.await?;let mca = state- .store+ .accounts_store.insert_merchant_connector_account(merchant_connector_account.clone(),processor.get_key_store(),@@ -2917,7 +2909,7 @@ pub async fn create_connector(let merchant_default_config_update = MerchantDefaultConfigUpdate {routable_connector: &routable_connector,merchant_connector_id: &mca.get_id(),- store,+ state: &state,merchant_id,profile_id: business_profile.get_id(),transaction_type: &req.get_transaction_type(),@@ -2930,7 +2922,7 @@ pub async fn create_connector(let merchant_default_config_update = DefaultFallbackRoutingConfigUpdate {routable_connector: &routable_connector,merchant_connector_id: &mca.get_id(),- store,+ state: &state,business_profile,key_store: processor.get_key_store().inner().to_owned(),key_manager_state,@@ -2969,9 +2961,7 @@ async fn validate_pm_auth(// Fetching disabled MCAs too: PM auth config may reference MCAs that are// temporarily disabled — validation checks existence, not activity.- let all_mcas = state- .store- .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(merchant_id, profile_id)+ let all_mcas = state.accounts_store.list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(merchant_id, profile_id).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: platform@@ -3001,9 +2991,8 @@ pub async fn retrieve_connector(profile_id: Option<id_type::ProfileId>,merchant_connector_id: id_type::MerchantConnectorAccountId,) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {- let store = state.store.as_ref();-- let mca = store+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(processor.get_account().get_id(),&merchant_connector_id,@@ -3026,11 +3015,10 @@ pub async fn retrieve_connector(processor: domain::Processor,id: id_type::MerchantConnectorAccountId,) -> RouterResponse<api_models::admin::MerchantConnectorResponse> {- let store = state.store.as_ref();-let merchant_id = processor.get_account().get_id();- let mca = store+ let mca = state+ .accounts_store.find_merchant_connector_account_by_id(&id, processor.get_key_store()).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {@@ -3060,8 +3048,8 @@ pub async fn list_connectors_for_a_profile(processor: domain::Processor,profile_id: id_type::ProfileId,) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> {- let store = state.store.as_ref();- let merchant_connector_accounts = store+ let merchant_connector_accounts = state+ .accounts_store.list_connector_account_by_profile_id(&profile_id, processor.get_key_store()).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;@@ -3079,9 +3067,8 @@ pub async fn list_payment_connectors(processor: domain::Processor,profile_id_list: Option<Vec<id_type::ProfileId>>,) -> RouterResponse<Vec<api_models::admin::MerchantConnectorListResponse>> {- let store = state.store.as_ref();-- let merchant_connector_accounts = store+ let merchant_connector_accounts = state+ .accounts_store.find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(processor.get_account().get_id(),true,@@ -3111,19 +3098,27 @@ pub async fn update_connector() -> RouterResponse<api_models::admin::MerchantConnectorResponse> {let db = state.store.as_ref();let key_manager_state = &(&state).into();- let key_store = db- .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;let mca = req.clone()- .get_merchant_connector_account_from_id(db, &merchant_id, merchant_connector_id, &key_store)+ .get_merchant_connector_account_from_id(+ state.accounts_store.as_ref(),+ &merchant_id,+ merchant_connector_id,+ &key_store,+ ).await?;core_utils::validate_profile_id_from_auth_layer(profile_id, &mca)?;@@ -3144,19 +3139,21 @@ pub async fn update_connector(let request_connector_label = req.connector_label;- let updated_mca = db- .update_merchant_connector_account(- mca.clone(),- behaviour::ForeignInto::foreign_into(payment_connector),- &key_store,- )- .await- .change_context(- errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {- profile_id: profile_id.get_string_repr().to_owned(),- connector_label: request_connector_label.unwrap_or_default(),- },- )+ let updated_mca =+ state+ .accounts_store+ .update_merchant_connector_account(+ mca.clone(),+ behaviour::ForeignInto::foreign_into(payment_connector),+ &key_store,+ )+ .await+ .change_context(+ errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {+ profile_id: profile_id.get_string_repr().to_owned(),+ connector_label: request_connector_label.unwrap_or_default(),+ },+ ).attach_printable_lazy(|| {format!("Failed while updating MerchantConnectorAccount: id: {merchant_connector_id:?}",@@ -3168,7 +3165,8 @@ pub async fn update_connector(// Fetch business profile for routing update#[cfg(feature = "v1")]- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(&key_store, &mca.profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -3186,7 +3184,7 @@ pub async fn update_connector(})?,),merchant_connector_id: &mca.get_id(),- store: db,+ state: &state,merchant_id: &merchant_id,profile_id: &mca.profile_id,transaction_type: &mca.connector_type.into(),@@ -3217,17 +3215,21 @@ pub async fn delete_connector(merchant_connector_id: id_type::MerchantConnectorAccountId,) -> RouterResponse<api::MerchantConnectorDeleteResponse> {let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let _merchant_account = db+ let _merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let mca = db+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(&merchant_id,&merchant_connector_id,@@ -3238,7 +3240,8 @@ pub async fn delete_connector(id: merchant_connector_id.get_string_repr().to_string(),})?;- let is_deleted = db+ let is_deleted = state+ .accounts_store.delete_merchant_connector_account_by_merchant_id_merchant_connector_id(&merchant_id,&merchant_connector_id,@@ -3249,7 +3252,8 @@ pub async fn delete_connector(})?;// Fetch business profile for routing update- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(&key_store, &mca.profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -3266,7 +3270,7 @@ pub async fn delete_connector(})?,),merchant_connector_id: &mca.get_id(),- store: db,+ state: &state,merchant_id: &merchant_id,profile_id: &mca.profile_id,transaction_type: &mca.connector_type.into(),@@ -3294,12 +3298,12 @@ pub async fn delete_connector(platform: domain::Platform,id: id_type::MerchantConnectorAccountId,) -> RouterResponse<api::MerchantConnectorDeleteResponse> {- let db = state.store.as_ref();let key_manager_state = &(&state).into();let merchant_id = platform.get_processor().get_account().get_id();- let mca = db+ let mca = state+ .accounts_store.find_merchant_connector_account_by_id(&id, platform.get_processor().get_key_store()).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {@@ -3318,14 +3322,16 @@ pub async fn delete_connector(.into());}- let is_deleted = db+ let is_deleted = state+ .accounts_store.delete_merchant_connector_account_by_id(&id).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: id.clone().get_string_repr().to_string(),})?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&mca.profile_id,@@ -3344,7 +3350,7 @@ pub async fn delete_connector()?,),merchant_connector_id: &mca.get_id(),- store: db,+ state: &state,business_profile,key_store: platform.get_processor().get_key_store().inner().to_owned(),key_manager_state,@@ -3368,13 +3374,16 @@ pub async fn kv_for_merchant(enable: bool,) -> RouterResponse<api_models::admin::ToggleKVResponse> {let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;// check if the merchant account exists- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -3391,24 +3400,28 @@ pub async fn kv_for_merchant(})?}- db.update_merchant(- merchant_account,- storage::MerchantAccountUpdate::StorageSchemeUpdate {- storage_scheme: MerchantStorageScheme::RedisKv,- },- &key_store,- )- .await+ state+ .accounts_store+ .update_merchant(+ merchant_account,+ storage::MerchantAccountUpdate::StorageSchemeUpdate {+ storage_scheme: MerchantStorageScheme::RedisKv,+ },+ &key_store,+ )+ .await}(false, MerchantStorageScheme::RedisKv) => {- db.update_merchant(- merchant_account,- storage::MerchantAccountUpdate::StorageSchemeUpdate {- storage_scheme: MerchantStorageScheme::PostgresOnly,- },- &key_store,- )- .await+ state+ .accounts_store+ .update_merchant(+ merchant_account,+ storage::MerchantAccountUpdate::StorageSchemeUpdate {+ storage_scheme: MerchantStorageScheme::PostgresOnly,+ },+ &key_store,+ )+ .await}}.map_err(|error| {@@ -3433,14 +3446,14 @@ pub async fn toggle_kv_for_all_merchants(state: SessionState,enable: bool,) -> RouterResponse<api_models::admin::ToggleAllKVResponse> {- let db = state.store.as_ref();let storage_scheme = if enable {MerchantStorageScheme::RedisKv} else {MerchantStorageScheme::PostgresOnly};- let total_update = db+ let total_update = state+ .accounts_store.update_all_merchant_account(storage::MerchantAccountUpdate::StorageSchemeUpdate {storage_scheme,})@@ -3464,13 +3477,16 @@ pub async fn check_merchant_account_kv_status(merchant_id: id_type::MerchantId,) -> RouterResponse<api_models::admin::ToggleKVResponse> {let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;// check if the merchant account exists- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -3523,7 +3539,7 @@ pub async fn create_and_insert_business_profile(let profile_name = business_profile_new.profile_name.clone();state- .store+ .accounts_store.insert_business_profile(key_store, business_profile_new).await.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {@@ -4047,8 +4063,6 @@ pub async fn create_profile(request: api::ProfileCreate,processor: domain::Processor,) -> RouterResponse<api_models::admin::ProfileResponse> {- let db = state.store.as_ref();-validate_external_vault_config_for_merchant_account_type(processor.get_account().merchant_account_type,request.is_external_vault_enabled,@@ -4071,7 +4085,8 @@ pub async fn create_profile(let profile_id = business_profile.get_id().to_owned();- let business_profile = db+ let business_profile = state+ .accounts_store.insert_business_profile(processor.get_key_store(), business_profile).await.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {@@ -4085,13 +4100,15 @@ pub async fn create_profile(#[cfg(feature = "v1")]if processor.get_account().default_profile.is_some() {let unset_default_profile = domain::MerchantAccountUpdate::UnsetDefaultProfile;- db.update_merchant(- processor.get_account().clone(),- unset_default_profile,- processor.get_key_store(),- )- .await- .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;+ state+ .accounts_store+ .update_merchant(+ processor.get_account().clone(),+ unset_default_profile,+ processor.get_key_store(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;}Ok(service_api::ApplicationResponse::Json(@@ -4108,11 +4125,14 @@ pub async fn list_profile(profile_id_list: Option<Vec<id_type::ProfileId>>,) -> RouterResponse<Vec<api_models::admin::ProfileResponse>> {let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let profiles = db+ let profiles = state+ .accounts_store.list_profile_by_merchant_id(&key_store, &merchant_id).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?@@ -4135,8 +4155,8 @@ pub async fn retrieve_profile(merchant_id: id_type::MerchantId,key_store: domain::MerchantKeyStore,) -> RouterResponse<api_models::admin::ProfileResponse> {- let db = state.store.as_ref();- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store, &merchant_id, &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -4164,8 +4184,8 @@ pub async fn delete_profile(profile_id: id_type::ProfileId,merchant_id: &id_type::MerchantId,) -> RouterResponse<bool> {- let db = state.store.as_ref();- let delete_result = db+ let delete_result = state+ .accounts_store.delete_profile_by_profile_id_merchant_id(&profile_id, merchant_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -4658,9 +4678,8 @@ pub async fn update_profile(request: api::ProfileUpdate,provider_merchant_id: Option<hyperswitch_domain_models::platform::ProviderMerchantId>,) -> RouterResponse<api::ProfileResponse> {- let db = state.store.as_ref();-- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -4670,7 +4689,8 @@ pub async fn update_profile(request.external_vault_connector_details.is_some(),)?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store, &merchant_id, profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -4708,7 +4728,8 @@ pub async fn update_profile(.get_update_profile_object(&state, &key_store, &business_profile).await?;- let updated_business_profile = db+ let updated_business_profile = state+ .accounts_store.update_profile_by_profile_id(&key_store, business_profile, profile_update).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -4750,12 +4771,13 @@ impl ProfileWrapper {pub async fn update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(self,- db: &dyn StorageInterface,+ state: &SessionState,key_manager_state: &KeyManagerState,merchant_key_store: &domain::MerchantKeyStore,algorithm_id: id_type::RoutingId,transaction_type: &storage::enums::TransactionType,) -> RouterResult<()> {+ let db = state.store.as_ref();let routing_cache_key = self.clone().get_routing_config_cache_key();let (routing_algorithm_id, payout_routing_algorithm_id) = match transaction_type {@@ -4773,7 +4795,9 @@ impl ProfileWrapper {let profile = self.profile;- db.update_profile_by_profile_id(merchant_key_store, profile, profile_update)+ state+ .accounts_store+ .update_profile_by_profile_id(merchant_key_store, profile, profile_update).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to update routing algorithm ref in business profile")?;@@ -4826,7 +4850,7 @@ impl ProfileWrapper {pub async fn update_default_fallback_routing_of_connectors_under_profile(self,- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,updated_config: &Vec<routing_types::RoutableConnectorChoice>,key_manager_state: &KeyManagerState,merchant_key_store: &domain::MerchantKeyStore,@@ -4849,7 +4873,7 @@ impl ProfileWrapper {}pub async fn update_revenue_recovery_algorithm_under_profile(self,- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,key_manager_state: &KeyManagerState,merchant_key_store: &domain::MerchantKeyStore,revenue_recovery_retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType,@@ -4879,17 +4903,16 @@ pub async fn extended_card_info_toggle(profile_id: &id_type::ProfileId,ext_card_info_choice: admin_types::ExtendedCardInfoChoice,) -> RouterResponse<admin_types::ExtendedCardInfoChoice> {- let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound).attach_printable("Error while fetching the key store by merchant_id")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(&key_store, profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -4905,7 +4928,9 @@ pub async fn extended_card_info_toggle(is_extended_card_info_enabled: ext_card_info_choice.enabled,};- db.update_profile_by_profile_id(&key_store, business_profile, profile_update)+ state+ .accounts_store+ .update_profile_by_profile_id(&key_store, business_profile, profile_update).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {id: profile_id.get_string_repr().to_owned(),@@ -4922,13 +4947,12 @@ pub async fn connector_agnostic_mit_toggle(profile_id: &id_type::ProfileId,connector_agnostic_mit_choice: admin_types::ConnectorAgnosticMitChoice,) -> RouterResponse<admin_types::ConnectorAgnosticMitChoice> {- let db = state.store.as_ref();-match processor.get_account().get_id() {processor_merchant_id if processor_merchant_id == merchant_id => {let key_store = processor.get_key_store();- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_merchant_id_profile_id(key_store, merchant_id, profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -4948,7 +4972,9 @@ pub async fn connector_agnostic_mit_toggle(is_connector_agnostic_mit_enabled: connector_agnostic_mit_choice.enabled,};- db.update_profile_by_profile_id(key_store, business_profile, profile_update)+ state+ .accounts_store+ .update_profile_by_profile_id(key_store, business_profile, profile_update).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {id: profile_id.get_string_repr().to_owned(),diff --git a/crates/router/src/core/analytics_report.rs b/crates/router/src/core/analytics_report.rsindex 2dc5e005c6..0d0265df64 100644--- a/crates/router/src/core/analytics_report.rs+++ b/crates/router/src/core/analytics_report.rs@@ -386,16 +386,13 @@ async fn payment_response_hash_key(let Some(merchant_id) = request.merchant_id.as_ref() else {return Ok(None);};+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.change_context(AnalyticsError::UnknownError)?;- crate::utils::get_payment_response_hash_key(state.store.as_ref(), &key_store, &request.auth)- .await+ crate::utils::get_payment_response_hash_key(state, &key_store, &request.auth).await}async fn send_emails(diff --git a/crates/router/src/core/apple_pay_certificates_migration.rs b/crates/router/src/core/apple_pay_certificates_migration.rsindex b825a610a2..1f74bd5821 100644--- a/crates/router/src/core/apple_pay_certificates_migration.rs+++ b/crates/router/src/core/apple_pay_certificates_migration.rs@@ -24,23 +24,20 @@ pub async fn apple_pay_certificates_migration(>,errors::ApiErrorResponse,> {- let db = state.store.as_ref();-let merchant_id_list = &req.merchant_ids;let mut migration_successful_merchant_ids = vec![];let mut migration_failed_merchant_ids = vec![];for merchant_id in merchant_id_list {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::InternalServerError)?;- let merchant_connector_accounts = db+ let merchant_connector_accounts = state+ .accounts_store.find_merchant_connector_account_by_merchant_id_and_disabled_list(merchant_id,true,@@ -88,7 +85,8 @@ pub async fn apple_pay_certificates_migration(}}- let merchant_connector_accounts_update = db+ let merchant_connector_accounts_update = state+ .accounts_store.update_multiple_merchant_connector_accounts(mca_to_update).await;diff --git a/crates/router/src/core/authentication.rs b/crates/router/src/core/authentication.rsindex 0891dc14f3..400acc246c 100644--- a/crates/router/src/core/authentication.rs+++ b/crates/router/src/core/authentication.rs@@ -427,17 +427,15 @@ whereif let Some(execution_mode) = execution_mode {let provider_merchant_id = payment_data.payment_intent.merchant_id.clone();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let provider_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &provider_merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&provider_merchant_id, &key_store_master_key).await.to_not_found_response(ApiErrorResponse::InternalServerError).attach_printable("Error while fetching the key store for provider merchant")?;let provider_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&provider_merchant_id, &provider_key_store).await.to_not_found_response(ApiErrorResponse::InternalServerError)@@ -460,7 +458,7 @@ wherelet external_vault_merchant_connector_account =payments_core::helpers::MerchantConnectorAccountType::DbVal(Box::new(state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_provider().get_account().get_id(),&external_vault_mca_id,@@ -1265,7 +1263,7 @@ async fn call_ucs_authenticate_proxy(let external_vault_merchant_connector_account =payments_core::helpers::MerchantConnectorAccountType::DbVal(Box::new(state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_provider().get_account().get_id(),&external_vault_mca_id,diff --git a/crates/router/src/core/blocklist/batch.rs b/crates/router/src/core/blocklist/batch.rsindex 4b59fdc08c..16958532a7 100644--- a/crates/router/src/core/blocklist/batch.rs+++ b/crates/router/src/core/blocklist/batch.rs@@ -359,7 +359,7 @@ pub async fn initiate_batch_blocklist_upload(None,platform.get_processor(),profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?.get_id()diff --git a/crates/router/src/core/blocklist/clone.rs b/crates/router/src/core/blocklist/clone.rsindex d976af4e3c..bb86a06147 100644--- a/crates/router/src/core/blocklist/clone.rs+++ b/crates/router/src/core/blocklist/clone.rs@@ -30,7 +30,7 @@ async fn resolve_clone_targets(target_profile_ids: &HashSet<id_type::ProfileId>,) -> RouterResult<Vec<id_type::ProfileId>> {let merchant_profile_ids = state- .store+ .accounts_store.list_profile_by_merchant_id(processor.get_key_store(), processor.get_account().get_id()).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/blocklist/export.rs b/crates/router/src/core/blocklist/export.rsindex 55f4fa7b2d..6eace63dd3 100644--- a/crates/router/src/core/blocklist/export.rs+++ b/crates/router/src/core/blocklist/export.rs@@ -82,7 +82,7 @@ pub async fn initiate_blocklist_export(None,platform.get_processor(),profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?.get_id()diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rsindex 18f510d091..569283c1af 100644--- a/crates/router/src/core/blocklist/utils.rs+++ b/crates/router/src/core/blocklist/utils.rs@@ -35,7 +35,7 @@ pub async fn delete_entry_from_blocklist(None,processor,profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?.get_id()@@ -201,7 +201,7 @@ pub async fn get_blocklist_count(None,processor,profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?.get_id()@@ -280,7 +280,7 @@ pub async fn lookup_blocklist_entry(None,processor,profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?.get_id()@@ -326,7 +326,7 @@ pub async fn insert_entry_into_blocklist(None,platform.get_processor(),profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?.get_id()diff --git a/crates/router/src/core/cards_info.rs b/crates/router/src/core/cards_info.rsindex 5d70ff5b9f..f1e2aaabea 100644--- a/crates/router/src/core/cards_info.rs+++ b/crates/router/src/core/cards_info.rs@@ -58,7 +58,7 @@ pub async fn create_card_info(card_info_request: cards_info_api_types::CardInfoCreateRequest,) -> RouterResponse<cards_info_api_types::CardInfoResponse> {let db = state.store.as_ref();- cards_info::CardsInfoInterface::add_card_info(db, card_info_request.foreign_into())+ cards_info::TrackedCardsInfoInterface::add_card_info(db, card_info_request.foreign_into()).await.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {message: "CardInfo with given key already exists in our records".to_string(),@@ -72,7 +72,7 @@ pub async fn update_card_info(card_info_request: cards_info_api_types::CardInfoUpdateRequest,) -> RouterResponse<cards_info_api_types::CardInfoResponse> {let db = state.store.as_ref();- cards_info::CardsInfoInterface::update_card_info(+ cards_info::TrackedCardsInfoInterface::update_card_info(db,card_info_request.card_iin,card_info_models::UpdateCardInfo {@@ -220,18 +220,20 @@ impl<'a> CardInfoMigrateExecutor<'a> {async fn add_card_info(&self) -> RouterResult<card_info_models::CardInfo> {let db = self.state.store.as_ref();- let card_info =- cards_info::CardsInfoInterface::add_card_info(db, self.record.clone().foreign_into())- .await- .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {- message: "CardInfo with given key already exists in our records".to_string(),- })?;+ let card_info = cards_info::TrackedCardsInfoInterface::add_card_info(+ db,+ self.record.clone().foreign_into(),+ )+ .await+ .to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {+ message: "CardInfo with given key already exists in our records".to_string(),+ })?;Ok(card_info)}async fn update_card_info(&self) -> RouterResult<card_info_models::CardInfo> {let db = self.state.store.as_ref();- let card_info = cards_info::CardsInfoInterface::update_card_info(+ let card_info = cards_info::TrackedCardsInfoInterface::update_card_info(db,self.record.card_iin.clone(),card_info_models::UpdateCardInfo {diff --git a/crates/router/src/core/conditional_config.rs b/crates/router/src/core/conditional_config.rsindex 1482ce7ec1..0fecf4b845 100644--- a/crates/router/src/core/conditional_config.rs+++ b/crates/router/src/core/conditional_config.rs@@ -24,7 +24,6 @@ pub async fn upsert_conditional_config(use common_utils::ext_traits::OptionExt;let key_manager_state: &KeyManagerState = &(&state).into();- let db = &*state.store;let name = request.name;let program = request.program;let timestamp = common_utils::date_time::now_unix_timestamp();@@ -44,7 +43,8 @@ pub async fn upsert_conditional_config(let business_profile_update = domain::ProfileUpdate::DecisionManagerRecordUpdate {three_ds_decision_manager_config: decision_manager_record,};- let updated_profile = db+ let updated_profile = state+ .accounts_store.update_profile_by_profile_id(&key_store, profile, business_profile_update).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/configs/payment_callback.rs b/crates/router/src/core/configs/payment_callback.rsindex b4ae405bfe..ff6385ea8b 100644--- a/crates/router/src/core/configs/payment_callback.rs+++ b/crates/router/src/core/configs/payment_callback.rs@@ -8,7 +8,7 @@//! `common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME` seconds.use error_stack::ResultExt;-use hyperswitch_domain_models::configs::ConfigInterface;+use hyperswitch_domain_models::configs::TrackedConfigInterface;use serde::Deserialize;use storage_impl::errors::StorageError;@@ -66,7 +66,7 @@ impl PaymentCallbackConfig {}async fn load_from_store(- store: &(impl ConfigInterface<Error = StorageError> + ?Sized),+ store: &(impl TrackedConfigInterface<Error = StorageError> + ?Sized),) -> RouterResult<Self> {let config = store.find_config_by_key_optional(Self::KEY)diff --git a/crates/router/src/core/debit_routing.rs b/crates/router/src/core/debit_routing.rsindex c933d54c94..ce2a9c787c 100644--- a/crates/router/src/core/debit_routing.rs+++ b/crates/router/src/core/debit_routing.rs@@ -303,11 +303,10 @@ wheredebit_routing_output.co_badged_card_networks_info);- let key_store = db- .get_merchant_key_store_by_merchant_id(- &processor_merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&processor_merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::MerchantAccountNotFound).map_err(|error| {@@ -568,11 +567,10 @@ whereif is_any_debit_routing_connector_supported {let debit_routing_output =get_debit_routing_output::<F, D>(state, payment_data, acquirer_country).await?;- let key_store = db- .get_merchant_key_store_by_merchant_id(- &processor_merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&processor_merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::MerchantAccountNotFound).map_err(|error| {@@ -652,7 +650,7 @@ async fn fetch_merchant_connector_accounts(key_store: &domain::MerchantKeyStore,) -> CustomResult<Vec<domain::MerchantConnectorAccount>, errors::ApiErrorResponse> {state- .store+ .accounts_store.list_enabled_connector_accounts_by_profile_id(profile_id,key_store,diff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rsindex dd79f80b3a..d732db3607 100644--- a/crates/router/src/core/disputes.rs+++ b/crates/router/src/core/disputes.rs@@ -137,7 +137,7 @@ pub async fn retrieve_dispute(})?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&payment_attempt.profile_id,@@ -351,7 +351,8 @@ pub async fn get_platform_disputes_filters(let db = state.store.as_ref();- let merchant_accounts = db+ let merchant_accounts = state+ .accounts_store.list_merchant_accounts_by_organization_id(platform.get_provider().get_account().get_org_id(),)@@ -364,11 +365,10 @@ pub async fn get_platform_disputes_filters(account.merchant_account_type == common_enums::MerchantAccountType::Connected}) {let merchant_id = connected_account.get_id().clone();- let key_store = db- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -957,7 +957,8 @@ pub async fn fetch_disputes_from_connector(req: FetchDisputesRequestData,) -> RouterResponse<FetchDisputesResponse> {let db = &*state.store;- let merchant_connector_account = db+ let merchant_connector_account = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_processor().get_account().get_id(),&merchant_connector_id,@@ -1245,27 +1246,24 @@ pub async fn schedule_dispute_sync_task(let processor_merchant_id = mca.merchant_id.clone();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let processor_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &processor_merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&processor_merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound).attach_printable("Error while fetching the key store for processor merchant")?;let processor_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&processor_merchant_id, &processor_key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound).attach_printable("Error while fetching the merchant account for processor")?;let organization = state- .track_accounts_query(|db| {- db.find_organization_by_org_id(processor_account.get_org_id())- })+ .accounts_store+ .find_organization_by_org_id(processor_account.get_org_id()).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Error while fetching the organization for processor merchant")?;diff --git a/crates/router/src/core/encryption.rs b/crates/router/src/core/encryption.rsindex e3270929d6..c5940b241d 100644--- a/crates/router/src/core/encryption.rs+++ b/crates/router/src/core/encryption.rs@@ -15,8 +15,10 @@ pub async fn transfer_encryption_key(req: MerchantKeyTransferRequest,) -> errors::CustomResult<usize, errors::ApiErrorResponse> {let db = &*state.store;- let key_stores = db- .get_all_key_stores(&db.get_master_key().to_vec().into(), req.from, req.limit)+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_stores = state+ .accounts_store+ .get_all_key_stores(&key_store_master_key, req.from, req.limit).await.change_context(errors::ApiErrorResponse::InternalServerError)?;send_request_to_key_service_for_merchant(state, key_stores).awaitdiff --git a/crates/router/src/core/external_service_auth.rs b/crates/router/src/core/external_service_auth.rsindex 366cc38bf7..929dac3499 100644--- a/crates/router/src/core/external_service_auth.rs+++ b/crates/router/src/core/external_service_auth.rs@@ -147,40 +147,41 @@ async fn resolve_offer_engine_merchant_id(.with_organization_id(payload.org_id.clone()).with_profile_id(payload.profile_id.clone());- let config =- match offer_engine::resolve_offer_engine_credential_source(state, &dimensions).await {- offer_engine::OfferEngineCredentialSource::None => {- return Err(error_stack::report!(- errors::ApiErrorResponse::AccessForbidden {- resource: "offer_engine".to_string(),- }- ));- }- offer_engine::OfferEngineCredentialSource::Application => {- offer_engine::OfferEngineCredentialSource::resolve_application_offer_config(state)- }- offer_engine::OfferEngineCredentialSource::Merchant => {- let db = &*state.store;- let key_store = db- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &db.get_master_key().to_vec().into(),- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)?;- let merchant_account = db- .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store)- .await- .change_context(errors::ApiErrorResponse::InternalServerError)?;- offer_engine::OfferEngineCredentialSource::resolve_merchant_offer_config(- state,- &merchant_account,- )- }+ let config = match offer_engine::resolve_offer_engine_credential_source(state, &dimensions)+ .await+ {+ offer_engine::OfferEngineCredentialSource::None => {+ return Err(error_stack::report!(+ errors::ApiErrorResponse::AccessForbidden {+ resource: "offer_engine".to_string(),+ }+ ));+ }+ offer_engine::OfferEngineCredentialSource::Application => {+ offer_engine::OfferEngineCredentialSource::resolve_application_offer_config(state)+ }+ offer_engine::OfferEngineCredentialSource::Merchant => {+ let db = &*state.store;+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let merchant_account = state+ .accounts_store+ .find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)?;+ offer_engine::OfferEngineCredentialSource::resolve_merchant_offer_config(+ state,+ &merchant_account,+ )}- .change_context(errors::ApiErrorResponse::AccessForbidden {- resource: "offer_engine".to_string(),- })?;+ }+ .change_context(errors::ApiErrorResponse::AccessForbidden {+ resource: "offer_engine".to_string(),+ })?;Ok(config.merchant_id)}diff --git a/crates/router/src/core/fraud_check.rs b/crates/router/src/core/fraud_check.rsindex 82a84f0bbf..d885a27ee0 100644--- a/crates/router/src/core/fraud_check.rs+++ b/crates/router/src/core/fraud_check.rs@@ -118,7 +118,7 @@ where.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("profile_id is not set in payment_intent")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_merchant_id_profile_id(platform.get_processor().get_key_store(),platform.get_processor().get_account().get_id(),@@ -515,7 +515,6 @@ where{use common_utils::ext_traits::OptionExt;- let db = &*state.store;match business_profile.frm_routing_algorithm.clone().or(platform.get_processor().get_account()@@ -541,7 +540,8 @@ where.clone();#[cfg(feature = "v1")]- let merchant_connector_account_from_db_option = db+ let merchant_connector_account_from_db_option = state+ .accounts_store.find_merchant_connector_account_by_profile_id_connector_name(&profile_id,&frm_routing_algorithm_struct.data,diff --git a/crates/router/src/core/gsm.rs b/crates/router/src/core/gsm.rsindex 7f96d0374d..51a15f0fb5 100644--- a/crates/router/src/core/gsm.rs+++ b/crates/router/src/core/gsm.rs@@ -4,7 +4,7 @@ use router_env::instrument;use crate::{core::errors::{self, RouterResponse, StorageErrorExt},- db::gsm::GsmInterface,+ db::gsm::TrackedGsmInterface,services,types::transformers::{ForeignFrom, ForeignInto},SessionState,@@ -16,7 +16,7 @@ pub async fn create_gsm_rule(gsm_rule: gsm_api_types::GsmCreateRequest,) -> RouterResponse<gsm_api_types::GsmResponse> {let db = state.store.as_ref();- GsmInterface::add_gsm_rule(db, gsm_rule.foreign_into())+ TrackedGsmInterface::add_gsm_rule(db, gsm_rule.foreign_into()).await.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {message: "GSM with given key already exists in our records".to_string(),@@ -37,7 +37,7 @@ pub async fn retrieve_gsm_rule(code,message,} = gsm_request;- GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message)+ TrackedGsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message).await.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {message: "GSM with given key does not exist in our records".to_string(),@@ -57,12 +57,18 @@ pub async fn update_gsm_rule(let sub_flow = gsm_request.sub_flow.clone();let message = gsm_request.message.clone();- let gsm_db_record =- GsmInterface::find_gsm_rule(db, connector.to_string(), flow, sub_flow, code, message)- .await- .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {- message: "GSM with given key does not exist in our records".to_string(),- })?;+ let gsm_db_record = TrackedGsmInterface::find_gsm_rule(+ db,+ connector.to_string(),+ flow,+ sub_flow,+ code,+ message,+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {+ message: "GSM with given key does not exist in our records".to_string(),+ })?;let inferred_feature_info = <(common_enums::GsmFeature,@@ -89,7 +95,7 @@ pub async fn update_gsm_rule(description,user_guidance_message,} = gsm_request;- GsmInterface::update_gsm_rule(+ TrackedGsmInterface::update_gsm_rule(db,connector.to_string(),flow,@@ -141,7 +147,7 @@ pub async fn delete_gsm_rule(code,message,} = gsm_request;- match GsmInterface::delete_gsm_rule(+ match TrackedGsmInterface::delete_gsm_rule(db,connector.to_string(),flow.to_owned(),diff --git a/crates/router/src/core/hierarchical_resources.rs b/crates/router/src/core/hierarchical_resources.rsindex e9dbe764ed..f61fd7788b 100644--- a/crates/router/src/core/hierarchical_resources.rs+++ b/crates/router/src/core/hierarchical_resources.rs@@ -17,7 +17,7 @@ use storage_impl::behaviour::ForeignInto;use crate::{core::errors::{self, RouterResponse, RouterResult, StorageErrorExt},- db::StorageInterface,+ db::AccountsStorageInterface,routes::SessionState,services::api::ApplicationResponse,types::domain,@@ -243,8 +243,6 @@ impl HierarchicalResourceHandler for ApplePayCertificateResource {account: RequestorAccount,account_key_store: &domain::MerchantKeyStore,) -> RouterResult<()> {- let db = state.store.as_ref();-match resource.encrypted_data.as_ref() {Some(private_key) => {let data = parse_apple_pay_certificate_data(&resource.data)?;@@ -290,8 +288,13 @@ impl HierarchicalResourceHandler for ApplePayCertificateResource {apple_pay_certificates: Some(Secret::new(plain_data)),apple_pay_certificates_encrypted: Some(encrypted_cache.into()),};- link_hierarchical_resource_data_to_scope(db, account_key_store, account, &update)- .await+ link_hierarchical_resource_data_to_scope(+ state.accounts_store.as_ref(),+ account_key_store,+ account,+ &update,+ )+ .await}None => Ok(()),}@@ -305,8 +308,6 @@ impl ApplePayCertificateResource {org_key: &Secret<Vec<u8>>,req: api_resources::UploadCertificateRequest,) -> RouterResult<api_resources::UploadCertificateResponse> {- let db = state.store.as_ref();-let private_key_payload = resource.encrypted_data.as_ref()@@ -345,20 +346,16 @@ impl ApplePayCertificateResource {payment_processing_certificate: Some(req.certificate),};- let updated = db- .update_linked_resource_data(- resource.id.clone(),- domain::HierarchicalResourceDataUpdate {- data: Secret::new(- serde_json::to_value(&data)- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Failed to serialize Apple Pay certificate resource data",- )?,- ),- },- org_key,- )+ let resource_update = domain::HierarchicalResourceDataUpdate {+ data: Secret::new(+ serde_json::to_value(&data)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialize Apple Pay certificate resource data")?,+ ),+ };+ let updated = state+ .accounts_store+ .update_linked_resource_data(resource.id.clone(), resource_update, org_key).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to persist uploaded Apple Pay certificate")?;@@ -437,7 +434,7 @@ where/// check is needed since the fetch can never return an entity belonging to a different merchant.#[cfg(feature = "v1")]async fn fetch_requestor_account(- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,processor: &domain::Processor,requestor_type: common_enums::ResourceRequestorType,requestor_id: &str,@@ -487,7 +484,7 @@ async fn fetch_requestor_account(#[cfg(feature = "v2")]async fn fetch_requestor_account(- _db: &dyn StorageInterface,+ _db: &dyn AccountsStorageInterface,_processor: &domain::Processor,_requestor_type: common_enums::ResourceRequestorType,_requestor_id: &str,@@ -503,7 +500,7 @@ async fn fetch_requestor_account(/// already scoped to `processor`'s merchant, not caller-supplied ids.#[cfg(feature = "v1")]async fn resolve_apple_pay_certificate_data(- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,processor: &domain::Processor,account: &RequestorAccount,) -> Option<serde_json::Value> {@@ -537,7 +534,7 @@ async fn resolve_apple_pay_certificate_data(#[cfg(feature = "v2")]async fn resolve_apple_pay_certificate_data(- _db: &dyn StorageInterface,+ _db: &dyn AccountsStorageInterface,_processor: &domain::Processor,_account: &RequestorAccount,) -> Option<serde_json::Value> {@@ -545,7 +542,7 @@ async fn resolve_apple_pay_certificate_data(}async fn link_hierarchical_resource_data_to_scope(- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,key_store: &domain::MerchantKeyStore,account: RequestorAccount,update: &impl RequestorHierarchicalResourceUpdate,@@ -583,12 +580,11 @@ pub async fn generate_hierarchical_resource(processor: domain::Processor,req: api_resources::GenerateHierarchicalResourceRequest,) -> RouterResponse<api_resources::GenerateHierarchicalResourceResponse> {- let db = state.store.as_ref();let key_manager_state: &KeyManagerState = &(&state).into();let organization_id = processor.get_account().organization_id.clone();let org_key_store =- ensure_organization_key_store(db, key_manager_state, &organization_id).await?;+ ensure_organization_key_store(&state, key_manager_state, &organization_id).await?;let (resource, response) = match req.resource_type {common_enums::ResourceType::ApplePayCertificate => {@@ -596,7 +592,9 @@ pub async fn generate_hierarchical_resource(}};- db.insert_linked_resource(resource, &org_key_store.key)+ state+ .accounts_store+ .insert_linked_resource(resource, &org_key_store.key).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to persist generated resource")?;@@ -635,11 +633,11 @@ pub async fn upload_hierarchical_resource(resource_id: id_type::ResourceId,req: api_resources::UploadCertificateRequest,) -> RouterResponse<api_resources::UploadCertificateResponse> {- let db = state.store.as_ref();let key_manager_state: &KeyManagerState = &(&state).into();let organization_id = processor.get_account().organization_id.clone();- let scope_id = db+ let scope_id = state+ .accounts_store.find_resource_scope_id(resource_id.clone()).await.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {@@ -648,9 +646,10 @@ pub async fn upload_hierarchical_resource(authorize_scope_id_belongs_to_org(&scope_id, &organization_id)?;let org_key_store =- ensure_organization_key_store(db, key_manager_state, &organization_id).await?;+ ensure_organization_key_store(&state, key_manager_state, &organization_id).await?;- let resource = db+ let resource = state+ .accounts_store.find_linked_resource_by_id(resource_id.clone(), &org_key_store.key).await.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {@@ -731,14 +730,14 @@ pub async fn list_hierarchical_resources(processor: domain::Processor,req: api_resources::ListHierarchicalResourcesRequest,) -> RouterResponse<api_resources::ListHierarchicalResourcesResponse> {- let db = state.store.as_ref();let key_manager_state: &KeyManagerState = &(&state).into();let organization_id = processor.get_account().organization_id.clone();let org_key_store =- ensure_organization_key_store(db, key_manager_state, &organization_id).await?;+ ensure_organization_key_store(&state, key_manager_state, &organization_id).await?;- let resources = db+ let resources = state+ .accounts_store.list_linked_resources_by_scope_id_and_resource_type(organization_id.get_string_repr().to_string(),req.resource_type.to_string(),@@ -750,8 +749,20 @@ pub async fn list_hierarchical_resources(let effective_resource_id = match (req.scope_type, req.scope_id) {(Some(scope_type), Some(scope_id)) => {- let account = fetch_requestor_account(db, &processor, scope_type, &scope_id).await?;- match resolve_apple_pay_certificate_data(db, &processor, &account).await {+ let account = fetch_requestor_account(+ state.accounts_store.as_ref(),+ &processor,+ scope_type,+ &scope_id,+ )+ .await?;+ match resolve_apple_pay_certificate_data(+ state.accounts_store.as_ref(),+ &processor,+ &account,+ )+ .await+ {Some(data) => data.get("resource_id").and_then(|value| value.as_str())@@ -814,12 +825,12 @@ pub async fn link_hierarchical_resource(resource_id: id_type::ResourceId,req: api_resources::LinkHierarchicalResourceRequest,) -> RouterResponse<api_resources::LinkHierarchicalResourceResponse> {- let db = state.store.as_ref();let key_manager_state: &KeyManagerState = &(&state).into();let merchant_account = processor.get_account();let organization_id = merchant_account.organization_id.clone();- let scope_id = db+ let scope_id = state+ .accounts_store.find_resource_scope_id(resource_id.clone()).await.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {@@ -827,13 +838,19 @@ pub async fn link_hierarchical_resource(})?;authorize_scope_id_belongs_to_org(&scope_id, &organization_id)?;- let account =- fetch_requestor_account(db, &processor, req.requestor_type, &req.requestor_id).await?;+ let account = fetch_requestor_account(+ state.accounts_store.as_ref(),+ &processor,+ req.requestor_type,+ &req.requestor_id,+ )+ .await?;let org_key_store =- ensure_organization_key_store(db, key_manager_state, &organization_id).await?;+ ensure_organization_key_store(&state, key_manager_state, &organization_id).await?;- let resource = db+ let resource = state+ .accounts_store.find_linked_resource_by_id(resource_id.clone(), &org_key_store.key).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -873,7 +890,7 @@ fn authorize_scope_id_belongs_to_org(}pub(crate) async fn ensure_organization_key_store(- db: &dyn StorageInterface,+ state: &SessionState,key_manager_state: &KeyManagerState,organization_id: &id_type::OrganizationId,) -> RouterResult<domain::MerchantKeyStore> {@@ -882,23 +899,30 @@ pub(crate) async fn ensure_organization_key_store(.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to derive organization key identifier")?;- let master_key = db.get_master_key();+ let master_key = state.store.get_master_key();- match db- .get_merchant_key_store_by_merchant_id(&org_key_identifier, &master_key.to_vec().into())+ let key_store_master_key = master_key.to_vec().into();+ match state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&org_key_identifier, &key_store_master_key).await{Ok(key_store) => Ok(key_store),Err(error) if error.current_context().is_db_not_found() => {- create_organization_key_store(db, key_manager_state, &org_key_identifier, master_key)- .await+ create_organization_key_store(+ state.accounts_store.as_ref(),+ key_manager_state,+ &org_key_identifier,+ master_key,+ )+ .await}Err(error) => Err(error).change_context(errors::ApiErrorResponse::InternalServerError),}}async fn create_organization_key_store(- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,key_manager_state: &KeyManagerState,org_key_identifier: &id_type::MerchantId,master_key: &[u8],@@ -936,7 +960,8 @@ async fn create_organization_key_store(created_at: date_time::now(),};- db.insert_merchant_key_store(key_store.clone(), &master_key.to_vec().into())+ let key_store_master_key = master_key.to_vec().into();+ db.insert_merchant_key_store(key_store.clone(), &key_store_master_key).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to insert organization key store")?;diff --git a/crates/router/src/core/merchant_connector_webhook_management.rs b/crates/router/src/core/merchant_connector_webhook_management.rsindex 81f47fa1e2..d1df59eb94 100644--- a/crates/router/src/core/merchant_connector_webhook_management.rs+++ b/crates/router/src/core/merchant_connector_webhook_management.rs@@ -182,12 +182,15 @@ pub async fn register_connector_webhook(api_models::merchant_connector_webhook_management::RegisterConnectorWebhookResponse,> {let db = state.store.as_ref();- let key_store = db- .get_merchant_key_store_by_merchant_id(merchant_id, &db.get_master_key().to_vec().into())+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let mca = db+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(merchant_id,merchant_connector_id,@@ -502,7 +505,9 @@ pub async fn register_connector_webhook();if should_update_db {- db.update_merchant_connector_account(mca.clone(), mca_update.foreign_into(), &key_store)+ state+ .accounts_store+ .update_merchant_connector_account(mca.clone(), mca_update.foreign_into(), &key_store).await.change_context(errors::ApiErrorResponse::DuplicateMerchantConnectorAccount {@@ -586,15 +591,15 @@ pub async fn fetch_connector_webhook() -> RouterResponse<api_models::merchant_connector_webhook_management::ConnectorWebhookListResponse>{let store = state.store.as_ref();- let key_store = store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &store.get_master_key().to_vec().into(),- )+ let key_store_master_key = store.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let mca = store+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(&merchant_id,&merchant_connector_id,diff --git a/crates/router/src/core/offer_engine/notify.rs b/crates/router/src/core/offer_engine/notify.rsindex 54e0bdf230..ebd11cfc88 100644--- a/crates/router/src/core/offer_engine/notify.rs+++ b/crates/router/src/core/offer_engine/notify.rs@@ -172,13 +172,16 @@ pub async fn execute_notification(let attributes = notify_attributes();let db = &*state.store;- let key_store = db+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&tracking_data.processor_merchant_id,- &db.get_master_key().to_vec().into(),+ &key_store_master_key,).await?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&tracking_data.processor_merchant_id, &key_store).await?;let processor_account = ProcessorMerchantAccount::from_untagged(merchant_account.clone());diff --git a/crates/router/src/core/payment_link.rs b/crates/router/src/core/payment_link.rsindex a29cd16d33..ddab9d202d 100644--- a/crates/router/src/core/payment_link.rs+++ b/crates/router/src/core/payment_link.rs@@ -175,7 +175,8 @@ pub async fn form_payment_link_data(.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("Profile id missing in payment link and payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(processor.get_key_store(), &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -999,7 +1000,8 @@ pub async fn get_payment_link_status(.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("Profile id missing in payment link and payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(processor.get_key_store(), &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {diff --git a/crates/router/src/core/payment_methods.rs b/crates/router/src/core/payment_methods.rsindex 57b69b87e9..b1d0c72a19 100644--- a/crates/router/src/core/payment_methods.rs+++ b/crates/router/src/core/payment_methods.rs@@ -4564,7 +4564,8 @@ pub async fn list_payment_methods_for_session(.change_context(errors::ApiErrorResponse::PaymentMethodNotFound).attach_printable("Unable to find payment method")?;- let payment_connector_accounts = db+ let payment_connector_accounts = state+ .accounts_store.list_enabled_connector_accounts_by_profile_id(profile.get_id(),platform.get_processor().get_key_store(),diff --git a/crates/router/src/core/payment_methods/cards.rs b/crates/router/src/core/payment_methods/cards.rsindex 1ec243742c..f3b5d22699 100644--- a/crates/router/src/core/payment_methods/cards.rs+++ b/crates/router/src/core/payment_methods/cards.rs@@ -4684,7 +4684,8 @@ pub async fn build_merchant_enabled_pms_context(// --- Load all MCAs and filter by connector type ---let profile_id = business_profile.get_id().clone();- let all_mcas = db+ let all_mcas = state+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(platform.get_processor().get_account().get_id(),&profile_id,@@ -5516,7 +5517,8 @@ pub async fn list_payment_methods(let (_profile_id, business_profile) =match payment_intent.as_ref().and_then(|pi| pi.profile_id.clone()) {Some(profile_id) => {- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&profile_id,@@ -6599,7 +6601,7 @@ pub async fn list_customer_payment_method(.transpose()?;let business_profile = core_utils::validate_and_get_business_profile(- db,+ state.accounts_store.as_ref(),platform.get_processor(),profile_id.as_ref(),)@@ -6613,12 +6615,10 @@ pub async fn list_customer_payment_method(// The MCA list is used to evaluate if the payment method has connector_mandate_details for any active MCAlet merchant_connector_accounts = match business_profile.as_ref() {Some(business_profile) => Some(- state- .store- .list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(- platform.get_processor().get_account().get_id(),- business_profile.get_id(),- )+ state.accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(+ platform.get_processor().get_account().get_id(),+ business_profile.get_id(),+ ).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {diff --git a/crates/router/src/core/payment_methods/client.rs b/crates/router/src/core/payment_methods/client.rsindex ecae6f8049..b4e63939dc 100644--- a/crates/router/src/core/payment_methods/client.rs+++ b/crates/router/src/core/payment_methods/client.rs@@ -288,7 +288,7 @@ impl CustomerPaymentMethodsFetcher for ModularCustomerPaymentMethodsFetcher {// issued a mandate token is still enabled for this profile — mirroring the// `get_mca_status` check performed in the legacy DB flow.let merchant_connector_accounts = state- .store+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(&merchant_id,&self.profile_id,@@ -430,7 +430,8 @@ async fn load_payment_intent_context(.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {diff --git a/crates/router/src/core/payment_methods/migration.rs b/crates/router/src/core/payment_methods/migration.rsindex 0cc92298e0..50d0ea2e92 100644--- a/crates/router/src/core/payment_methods/migration.rs+++ b/crates/router/src/core/payment_methods/migration.rs@@ -149,7 +149,8 @@ pub async fn update_payment_method_record(let mut cache = HashMap::new();for merchant_connector_id in parsed_mca_ids {- let mca = db+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_processor().get_account().get_id(),&merchant_connector_id,diff --git a/crates/router/src/core/payments.rs b/crates/router/src/core/payments.rsindex f12737cbe7..a29a5e561b 100644--- a/crates/router/src/core/payments.rs+++ b/crates/router/src/core/payments.rs@@ -3764,7 +3764,7 @@ wherelet external_vault_merchant_connector_account =helpers::MerchantConnectorAccountType::DbVal(Box::new(state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_provider().get_account().get_id(),&external_vault_mca_id,@@ -4052,12 +4052,10 @@ async fn is_clear_pan_retry_enabled_for_profile(network_token_response: &payments_api::PaymentsResponse,) -> bool {match network_token_response.profile_id.as_ref() {- Some(profile_id) => state- .store- .find_business_profile_by_profile_id(- platform.get_processor().get_key_store(),- profile_id,- )+ Some(profile_id) => state.accounts_store.find_business_profile_by_profile_id(+ platform.get_processor().get_key_store(),+ profile_id,+ ).await.map(|business_profile| business_profile.is_clear_pan_retries_enabled).inspect_err(|error| {@@ -4734,7 +4732,7 @@ pub async fn revenue_recovery_get_intent_core(let billing_mca_id = payment_intent.get_billing_merchant_connector_account_id();let max_retry_threshold = if let Some(billing_mca_id) = billing_mca_id {state- .store+ .accounts_store.find_merchant_connector_account_by_id(&billing_mca_id,platform.get_processor().get_key_store(),@@ -5402,7 +5400,7 @@ impl PaymentRedirectFlow for PaymentRedirectCompleteAuthorize {.as_ref().get_required_value("profile_id")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,@@ -5600,7 +5598,7 @@ impl PaymentRedirectFlow for PaymentRedirectSync {.as_ref().get_required_value("profile_id")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,@@ -5892,15 +5890,16 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {.authentication_id.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("missing authentication_id in payment_attempt")?;+ let profile_id = payment_intent+ .profile_id+ .as_ref()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("missing profile_id in payment_intent")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),- payment_intent- .profile_id- .as_ref()- .ok_or(errors::ApiErrorResponse::InternalServerError)- .attach_printable("missing profile_id in payment_intent")?,+ profile_id,).await.change_context(errors::ApiErrorResponse::ProfileNotFound {@@ -6181,7 +6180,7 @@ impl PaymentRedirectFlow for PaymentAuthenticateCompleteAuthorize {.as_ref().get_required_value("profile_id")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,@@ -9216,7 +9215,7 @@ pub async fn get_session_token_for_click_to_pay(field_name: "authentication_product_ids".into(),})?;let merchant_connector_account = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(processor.get_account().get_id(),&click_to_pay_mca_id,@@ -9292,7 +9291,7 @@ async fn get_card_brands_based_on_active_merchant_connector_account(processor: &domain::Processor,) -> RouterResult<HashSet<enums::CardNetwork>> {let merchant_configured_payment_connectors = state- .store+ .accounts_store.list_enabled_connector_accounts_by_profile_id(profile_id,processor.get_key_store(),@@ -9629,7 +9628,7 @@ wherelet merchant_id = processor.get_processor_merchant_id();let connector_mca = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(&merchant_id,&authentication_connector_id,@@ -10915,13 +10914,11 @@ async fn decrypt_apple_pay_wallet_for_eligibility(merchant_connector_id: &id_type::MerchantConnectorAccountId,apple_pay_wallet_data: &domain::ApplePayWalletData,) -> RouterResult<Option<domain::EligibilityPaymentMethodData>> {- let payment_processing_details = state- .store- .find_by_merchant_connector_account_merchant_id_merchant_connector_id(- processor.get_account().get_id(),- merchant_connector_id,- processor.get_key_store(),- )+ let payment_processing_details = state.accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ processor.get_account().get_id(),+ merchant_connector_id,+ processor.get_key_store(),+ ).await.inspect_err(|error| {logger::warn!(@@ -10990,13 +10987,11 @@ async fn decrypt_google_pay_wallet_for_eligibility(merchant_connector_id: &id_type::MerchantConnectorAccountId,google_pay_wallet_data: &domain::GooglePayWalletData,) -> RouterResult<Option<domain::EligibilityPaymentMethodData>> {- let payment_processing_details = state- .store- .find_by_merchant_connector_account_merchant_id_merchant_connector_id(- processor.get_account().get_id(),- merchant_connector_id,- processor.get_key_store(),- )+ let payment_processing_details = state.accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ processor.get_account().get_id(),+ merchant_connector_id,+ processor.get_key_store(),+ ).await.inspect_err(|error| {logger::warn!(@@ -14155,7 +14150,7 @@ pub async fn payment_external_authentication<F: Clone + Sync>(.await?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), profile_id).await.change_context(errors::ApiErrorResponse::ProfileNotFound {@@ -14549,17 +14544,15 @@ pub async fn payments_manual_update(update_amount_captured,amount_captured,} = req;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound).attach_printable("Error while fetching the key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)@@ -14826,18 +14819,16 @@ pub async fn payments_manual_status_update_eligible_statuses() -> RouterResponse<api_models::payments::PaymentsManualStatusUpdateEligibleStatusesResponse> {let merchant_id = platform.get_processor().get_processor_merchant_id();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound).attach_printable("Error while fetching the key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)@@ -14909,18 +14900,16 @@ pub async fn payments_manual_status_update(let merchant_id = platform.get_processor().get_processor_merchant_id();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound).attach_printable("Error while fetching the key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)@@ -15369,7 +15358,7 @@ pub async fn payments_submit_eligibility_check(.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -15907,7 +15896,7 @@ pub async fn payments_submit_eligibility(.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {diff --git a/crates/router/src/core/payments/filters.rs b/crates/router/src/core/payments/filters.rsindex c307724855..3806dabd05 100644--- a/crates/router/src/core/payments/filters.rs+++ b/crates/router/src/core/payments/filters.rs@@ -41,7 +41,8 @@ pub async fn get_platform_payment_filters(let db = state.store.as_ref();// Every connected merchant lives under the platform's organization.- let merchant_accounts = db+ let merchant_accounts = state+ .accounts_store.list_merchant_accounts_by_organization_id(platform.get_provider().get_account().get_org_id(),)@@ -58,11 +59,10 @@ pub async fn get_platform_payment_filters(account.merchant_account_type == common_enums::MerchantAccountType::Connected}) {let merchant_id = connected_account.get_id().clone();- let key_store = db- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;diff --git a/crates/router/src/core/payments/helpers.rs b/crates/router/src/core/payments/helpers.rsindex 99b82c3481..00aee6770d 100644--- a/crates/router/src/core/payments/helpers.rs+++ b/crates/router/src/core/payments/helpers.rs@@ -575,22 +575,20 @@ pub async fn get_token_pm_type_mandate_details(}RecurringDetails::ProcessorPaymentToken(processor_payment_token) => {if let Some(mca_id) = &processor_payment_token.merchant_connector_id {- let db = &*state.store;-#[cfg(feature = "v1")]- let connector_name = db- .find_by_merchant_connector_account_merchant_id_merchant_connector_id(- platform.get_processor().get_account().get_id(),- mca_id,- platform.get_processor().get_key_store(),- )+ let connector_name = state.accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ platform.get_processor().get_account().get_id(),+ mca_id,+ platform.get_processor().get_key_store(),+ ).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: mca_id.clone().get_string_repr().to_string(),})?.connector_name;#[cfg(feature = "v2")]- let connector_name = db+ let connector_name = state+ .accounts_store.find_merchant_connector_account_by_id(mca_id, merchant_key_store).await.to_not_found_response(@@ -3406,7 +3404,7 @@ pub async fn resolve_provider_profile(})?;state- .store+ .accounts_store.find_business_profile_by_profile_id(provider.get_key_store(), &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -3418,7 +3416,7 @@ pub async fn resolve_provider_profile(// v2 MerchantAccount has no `default_profile`; resolve the provider's single business// profile (which holds provider-level config, e.g. external vault) by listing its profiles.let profiles = state- .store+ .accounts_store.list_profile_by_merchant_id(provider.get_key_store(),provider.get_account().get_id(),@@ -3444,7 +3442,7 @@ pub async fn get_provider_mca_v2(.get_required_value("merchant_connector_id").attach_printable("merchant_connector_id not provided")?;state- .store+ .accounts_store.find_merchant_connector_account_by_id(merchant_connector_id, provider.get_key_store()).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {@@ -3530,7 +3528,7 @@ pub async fn fetch_card_details_from_external_vault(external_vault_mca_id: &id_type::MerchantConnectorAccountId,) -> RouterResult<domain::Card> {let merchant_connector_account_details = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(merchant_id,external_vault_mca_id,@@ -5303,48 +5301,54 @@ pub async fn get_merchant_connector_account(if let Some(merchant_connector_id) = merchant_connector_id {#[cfg(feature = "v1")]{- db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(- processor.get_account().get_id(),- merchant_connector_id,- processor.get_key_store(),- )- .await- .to_not_found_response(- errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: merchant_connector_id.get_string_repr().to_string(),- },- )+ state+ .accounts_store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ processor.get_account().get_id(),+ merchant_connector_id,+ processor.get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: merchant_connector_id.get_string_repr().to_string(),+ },+ )}#[cfg(feature = "v2")]{- db.find_merchant_connector_account_by_id(- merchant_connector_id,- processor.get_key_store(),- )- .await- .to_not_found_response(- errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: merchant_connector_id.get_string_repr().to_string(),- },- )+ state+ .accounts_store+ .find_merchant_connector_account_by_id(+ merchant_connector_id,+ processor.get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: merchant_connector_id.get_string_repr().to_string(),+ },+ )}} else {#[cfg(feature = "v1")]{- db.find_merchant_connector_account_by_profile_id_connector_name(- profile_id,- connector_name,- processor.get_key_store(),- )- .await- .to_not_found_response(- errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: format!(- "profile id {} and connector name {connector_name}",- profile_id.get_string_repr()- ),- },- )+ state+ .accounts_store+ .find_merchant_connector_account_by_profile_id_connector_name(+ profile_id,+ connector_name,+ processor.get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: format!(+ "profile id {} and connector name {connector_name}",+ profile_id.get_string_repr()+ ),+ },+ )}#[cfg(feature = "v2")]{@@ -7158,7 +7162,7 @@ pub async fn get_apple_pay_retryable_connectors(.as_ref(),)? {let merchant_connector_account_list = state- .store+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(processor.get_account().get_id(),profile_id,@@ -9306,7 +9310,7 @@ pub async fn fetch_active_surcharge_mca(surcharge_connector_id: &id_type::MerchantConnectorAccountId,) -> RouterResult<Option<domain::MerchantConnectorAccount>> {let surcharge_mca = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(merchant_id,surcharge_connector_id,@@ -9520,8 +9524,8 @@ pub async fn validate_merchant_connector_ids_in_connector_mandate_details(merchant_id: &id_type::MerchantId,card_network: Option<api_enums::CardNetwork>,) -> CustomResult<(), errors::ApiErrorResponse> {- let db = &*state.store;- let merchant_connector_account_list = db+ let merchant_connector_account_list = state+ .accounts_store.find_merchant_connector_account_without_encrypted_by_merchant_id_and_disabled_list(merchant_id,true,@@ -9838,8 +9842,8 @@ pub async fn validate_allowed_payment_method_types_request(allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>,) -> CustomResult<(), errors::ApiErrorResponse> {if let Some(allowed_payment_method_types) = allowed_payment_method_types {- let db = &*state.store;- let all_connector_accounts = db+ let all_connector_accounts = state+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(processor.get_account().get_id(),profile_id,@@ -9964,9 +9968,9 @@ pub async fn get_merchant_connector_account_v2(processor: &domain::Processor,merchant_connector_id: Option<&id_type::MerchantConnectorAccountId>,) -> RouterResult<domain::MerchantConnectorAccount> {- let db = &*state.store;match merchant_connector_id {- Some(merchant_connector_id) => db+ Some(merchant_connector_id) => state+ .accounts_store.find_merchant_connector_account_by_id(merchant_connector_id, processor.get_key_store()).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {diff --git a/crates/router/src/core/payments/list.rs b/crates/router/src/core/payments/list.rsindex 5216a77bf2..82598d9629 100644--- a/crates/router/src/core/payments/list.rs+++ b/crates/router/src/core/payments/list.rs@@ -275,14 +275,17 @@ pub async fn revenue_recovery_list_payments(.into_iter().map(|billing_mca_id| {let platform_clone = platform.clone(); // Clone for each future+ let state = &state;async move {if let Some(billing_mca_id) = billing_mca_id {- db.find_merchant_connector_account_by_id(- &billing_mca_id,- platform_clone.get_processor().get_key_store(),- )- .await- .ok()+ state+ .accounts_store+ .find_merchant_connector_account_by_id(+ &billing_mca_id,+ platform_clone.get_processor().get_key_store(),+ )+ .await+ .ok()} else {None}diff --git a/crates/router/src/core/payments/operations/payment_approve.rs b/crates/router/src/core/payments/operations/payment_approve.rsindex 628df1bdc7..d4a3a253b7 100644--- a/crates/router/src/core/payments/operations/payment_approve.rs+++ b/crates/router/src/core/payments/operations/payment_approve.rs@@ -88,7 +88,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCaptureR.attach_printable("'profile_id' not set in payment intent")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_cancel.rs b/crates/router/src/core/payments/operations/payment_cancel.rsindex 470d0ff5cf..3033e090db 100644--- a/crates/router/src/core/payments/operations/payment_cancel.rs+++ b/crates/router/src/core/payments/operations/payment_cancel.rs@@ -188,7 +188,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelRe.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rsindex 23fddd5b73..80973d91f7 100644--- a/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs+++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture.rs@@ -139,7 +139,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsCancelPo.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_cancel_post_capture_sync.rs b/crates/router/src/core/payments/operations/payment_cancel_post_capture_sync.rsindex 22746ccbf7..89a23b7c5b 100644--- a/crates/router/src/core/payments/operations/payment_cancel_post_capture_sync.rs+++ b/crates/router/src/core/payments/operations/payment_cancel_post_capture_sync.rs@@ -133,7 +133,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, id_type::PaymentId>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_capture.rs b/crates/router/src/core/payments/operations/payment_capture.rsindex 9b7c1ec1d5..d59e2374a2 100644--- a/crates/router/src/core/payments/operations/payment_capture.rs+++ b/crates/router/src/core/payments/operations/payment_capture.rs@@ -244,7 +244,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, payments::PaymentData<F>, api::Paymen.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_complete_authorize.rs b/crates/router/src/core/payments/operations/payment_complete_authorize.rsindex 66835ddb29..21ad0adf68 100644--- a/crates/router/src/core/payments/operations/payment_complete_authorize.rs+++ b/crates/router/src/core/payments/operations/payment_complete_authorize.rs@@ -350,7 +350,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_confirm.rs b/crates/router/src/core/payments/operations/payment_confirm.rsindex 3454e4904e..14209c4b79 100644--- a/crates/router/src/core/payments/operations/payment_confirm.rs+++ b/crates/router/src/core/payments/operations/payment_confirm.rs@@ -214,7 +214,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let store = state.store.clone();+ let profile_state = state.clone();let key_store_clone = platform.get_processor().get_key_store().clone();// Each fork below gets its own span rather than the caller's. These are@@ -225,7 +225,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>// naming each fork writes it down.let business_profile_fut = tokio::spawn(async move {- store+ profile_state+ .accounts_store.find_business_profile_by_profile_id(&key_store_clone, &profile_id).map(|business_profile_result| {business_profile_result.to_not_found_response(@@ -2065,13 +2066,11 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forfield_name: "authentication_product_ids".into(),})?;let merchant_id = &business_profile.merchant_id;- let connector_mca = state- .store- .find_by_merchant_connector_account_merchant_id_merchant_connector_id(- merchant_id,- &click_to_pay_mca_id,- platform.get_processor().get_key_store(),- )+ let connector_mca = state.accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ merchant_id,+ &click_to_pay_mca_id,+ platform.get_processor().get_key_store(),+ ).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {diff --git a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rsindex 0fa276a6ca..83cbacdebb 100644--- a/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs+++ b/crates/router/src/core/payments/operations/payment_confirm_external_vault_proxy.rs@@ -348,7 +348,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsRequest>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,@@ -1003,7 +1004,7 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsRequest, PaymentData<F>>.get_required_value("external vault connector id")?;let vault_mca = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_processor().get_account().get_id(),&vault_connector_id,diff --git a/crates/router/src/core/payments/operations/payment_create.rs b/crates/router/src/core/payments/operations/payment_create.rsindex cf1116cc1b..cd8929e5d5 100644--- a/crates/router/src/core/payments/operations/payment_create.rs+++ b/crates/router/src/core/payments/operations/payment_create.rs@@ -116,7 +116,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>request.business_label.as_ref(),platform.get_processor(),request.profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?}@@ -876,15 +876,14 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.payment_intent.is_settlement_conclusion_applied(){- let db = state.store.as_ref();-let merchant_connector_id = business_profile.tax_connector_id.as_ref().get_required_value("business_profile.tax_connector_id")?;#[cfg(feature = "v1")]- let mca = db+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(&business_profile.merchant_id,merchant_connector_id,@@ -898,7 +897,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for)?;#[cfg(feature = "v2")]- let mca = db+ let mca = state+ .accounts_store.find_merchant_connector_account_by_id(merchant_connector_id, key_store).await.to_not_found_response(@@ -972,7 +972,7 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> forreq.business_label.as_ref(),platform.get_processor(),req.profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?;helpers::validate_payment_profile(diff --git a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs b/crates/router/src/core/payments/operations/payment_post_session_tokens.rsindex 0399cc211d..521cf128f8 100644--- a/crates/router/src/core/payments/operations/payment_post_session_tokens.rs+++ b/crates/router/src/core/payments/operations/payment_post_session_tokens.rs@@ -103,7 +103,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsPostSess.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_recurrence.rs b/crates/router/src/core/payments/operations/payment_recurrence.rsindex 1a58683206..011ae61e15 100644--- a/crates/router/src/core/payments/operations/payment_recurrence.rs+++ b/crates/router/src/core/payments/operations/payment_recurrence.rs@@ -117,7 +117,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;let key_store_clone = platform.get_processor().get_key_store().clone();- let business_profile = store+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(&key_store_clone, &profile_id).map(|business_profile_result| {business_profile_result.to_not_found_response(diff --git a/crates/router/src/core/payments/operations/payment_reject.rs b/crates/router/src/core/payments/operations/payment_reject.rsindex da5e85dbc1..edef7693c6 100644--- a/crates/router/src/core/payments/operations/payment_reject.rs+++ b/crates/router/src/core/payments/operations/payment_reject.rs@@ -150,7 +150,7 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, PaymentsCancelRequest.attach_printable("'profile_id' not set in payment intent")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_session.rs b/crates/router/src/core/payments/operations/payment_session.rsindex 2acb0e7533..c5ef4a9950 100644--- a/crates/router/src/core/payments/operations/payment_session.rs+++ b/crates/router/src/core/payments/operations/payment_session.rs@@ -172,7 +172,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionR.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,@@ -410,8 +411,6 @@ whererequest: &api::PaymentsSessionRequest,payment_intent: &storage::PaymentIntent,) -> RouterResult<api::ConnectorChoice> {- let db = &state.store;-let profile_id = payment_intent.profile_id.clone()@@ -419,7 +418,8 @@ where.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("profile_id is not set in payment_intent")?;- let all_connector_accounts = db+ let all_connector_accounts = state+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(processor.get_account().get_id(),&profile_id,diff --git a/crates/router/src/core/payments/operations/payment_session_intent.rs b/crates/router/src/core/payments/operations/payment_session_intent.rsindex 89b7c14607..0655409222 100644--- a/crates/router/src/core/payments/operations/payment_session_intent.rs+++ b/crates/router/src/core/payments/operations/payment_session_intent.rs@@ -274,9 +274,9 @@ impl<F: Clone + Send + Sync> Domain<F, PaymentsSessionRequest, payments::Paymentstate: &SessionState,payment_data: &mut payments::PaymentIntentData<F>,) -> CustomResult<api::ConnectorCallType, errors::ApiErrorResponse> {- let db = &state.store;let profile_id = business_profile.get_id();- let all_connector_accounts = db+ let all_connector_accounts = state+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(platform.get_processor().get_account().get_id(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_start.rs b/crates/router/src/core/payments/operations/payment_start.rsindex a145b9ad49..6e375065d5 100644--- a/crates/router/src/core/payments/operations/payment_start.rs+++ b/crates/router/src/core/payments/operations/payment_start.rs@@ -173,7 +173,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsStartReq.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payment_status.rs b/crates/router/src/core/payments/operations/payment_status.rsindex ba1e092b23..911a7e3c9e 100644--- a/crates/router/src/core/payments/operations/payment_status.rs+++ b/crates/router/src/core/payments/operations/payment_status.rs@@ -478,7 +478,8 @@ async fn get_tracker_for_sync<.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {diff --git a/crates/router/src/core/payments/operations/payment_update.rs b/crates/router/src/core/payments/operations/payment_update.rsindex 074752e89a..b305a32ce4 100644--- a/crates/router/src/core/payments/operations/payment_update.rs+++ b/crates/router/src/core/payments/operations/payment_update.rs@@ -463,7 +463,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,@@ -726,15 +727,14 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for.payment_intent.is_settlement_conclusion_applied(){- let db = state.store.as_ref();-let merchant_connector_id = business_profile.tax_connector_id.as_ref().get_required_value("business_profile.tax_connector_id")?;#[cfg(feature = "v1")]- let mca = db+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(&business_profile.merchant_id,merchant_connector_id,@@ -748,7 +748,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for)?;#[cfg(feature = "v2")]- let mca = db+ let mca = state+ .accounts_store.find_merchant_connector_account_by_id(merchant_connector_id, key_store).await.to_not_found_response(diff --git a/crates/router/src/core/payments/operations/payment_update_metadata.rs b/crates/router/src/core/payments/operations/payment_update_metadata.rsindex 4c2f196848..d8d4a616a8 100644--- a/crates/router/src/core/payments/operations/payment_update_metadata.rs+++ b/crates/router/src/core/payments/operations/payment_update_metadata.rs@@ -101,7 +101,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsUpdateMe.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payments_extend_authorization.rs b/crates/router/src/core/payments/operations/payments_extend_authorization.rsindex f358d879ee..3f4e1dd6ae 100644--- a/crates/router/src/core/payments/operations/payments_extend_authorization.rs+++ b/crates/router/src/core/payments/operations/payments_extend_authorization.rs@@ -145,7 +145,8 @@ impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsExtendAu.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs b/crates/router/src/core/payments/operations/payments_incremental_authorization.rsindex 5ba4fe3d74..8fc0b1b398 100644--- a/crates/router/src/core/payments/operations/payments_incremental_authorization.rs+++ b/crates/router/src/core/payments/operations/payments_incremental_authorization.rs@@ -126,7 +126,7 @@ impl<F: Send + Clone + Sync>.attach_printable("'profile_id' not set in payment intent")?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,diff --git a/crates/router/src/core/payments/operations/tax_calculation.rs b/crates/router/src/core/payments/operations/tax_calculation.rsindex b11a7e0a58..1e6e7dfcad 100644--- a/crates/router/src/core/payments/operations/tax_calculation.rs+++ b/crates/router/src/core/payments/operations/tax_calculation.rs@@ -135,7 +135,8 @@ impl<F: Send + Clone + Sync>.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("'profile_id' not set in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),profile_id,@@ -265,15 +266,14 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsDynamicTaxCalculationRequest.payment_intent.is_settlement_conclusion_applied(){- let db = state.store.as_ref();-let merchant_connector_id = business_profile.tax_connector_id.as_ref().get_required_value("business_profile.tax_connector_id")?;#[cfg(feature = "v1")]- let mca = db+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(&business_profile.merchant_id,merchant_connector_id,@@ -287,7 +287,8 @@ impl<F: Clone + Send + Sync> Domain<F, api::PaymentsDynamicTaxCalculationRequest)?;#[cfg(feature = "v2")]- let mca = db+ let mca = state+ .accounts_store.find_merchant_connector_account_by_id(merchant_connector_id, key_store).await.to_not_found_response(diff --git a/crates/router/src/core/payments/payment_methods.rs b/crates/router/src/core/payments/payment_methods.rsindex fe1431d2ec..7b2f80f17f 100644--- a/crates/router/src/core/payments/payment_methods.rs+++ b/crates/router/src/core/payments/payment_methods.rs@@ -44,7 +44,8 @@ pub async fn list_payment_methods(validate_payment_status_for_payment_method_list(payment_intent.status)?;- let payment_connector_accounts = db+ let payment_connector_accounts = state+ .accounts_store.list_enabled_connector_accounts_by_profile_id(profile.get_id(),platform.get_processor().get_key_store(),diff --git a/crates/router/src/core/payments/routing.rs b/crates/router/src/core/payments/routing.rsindex 2c159cf516..85f90b3d20 100644--- a/crates/router/src/core/payments/routing.rs+++ b/crates/router/src/core/payments/routing.rs@@ -2384,7 +2384,7 @@ pub async fn refresh_cgraph_cache(// reusing a caller-supplied snapshot, so the cached graph is always built from// live data and cannot be poisoned by a stale pre-eviction snapshot.let mut merchant_connector_accounts = state- .store+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(&key_store.merchant_id,profile_id,@@ -4476,7 +4476,7 @@ pub async fn get_active_merchant_connector_accounts(profile_id: &common_utils::id_type::ProfileId,) -> RoutingResult<domain::MerchantConnectorAccountsWithoutEncrypted> {state- .store+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(&key_store.merchant_id,profile_id,diff --git a/crates/router/src/core/payments/tokenization.rs b/crates/router/src/core/payments/tokenization.rsindex b466bf9dfa..2c9f9d24a8 100644--- a/crates/router/src/core/payments/tokenization.rs+++ b/crates/router/src/core/payments/tokenization.rs@@ -1608,7 +1608,7 @@ pub async fn save_in_locker_external(let external_vault_mca_id = external_vault_connector_details.vault_connector_id.clone();let merchant_connector_account_details = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(provider.get_account().get_id(),&external_vault_mca_id,diff --git a/crates/router/src/core/payout_link.rs b/crates/router/src/core/payout_link.rsindex d852426aca..c1bc8e34be 100644--- a/crates/router/src/core/payout_link.rs+++ b/crates/router/src/core/payout_link.rs@@ -340,9 +340,9 @@ pub async fn filter_payout_methods()> {use hyperswitch_masking::ExposeInterface;- let db = &*state.store;//Fetch all merchant connector accounts- let all_mcas = db+ let all_mcas = state+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(platform.get_processor().get_account().get_id(),&payout.profile_id,diff --git a/crates/router/src/core/payouts.rs b/crates/router/src/core/payouts.rsindex 2667dc4270..6f61c535b0 100644--- a/crates/router/src/core/payouts.rs+++ b/crates/router/src/core/payouts.rs@@ -666,7 +666,7 @@ pub async fn payouts_create_core_wrapper(req.business_label.as_ref(),platform.get_processor(),req.profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?}@@ -4293,14 +4293,18 @@ async fn validate_and_get_business_profile(processor: &domain::Processor,profile_id: &id_type::ProfileId,) -> RouterResult<domain::Profile> {- let db = &*state.store;-- if let Some(business_profile) =- core_utils::validate_and_get_business_profile(db, processor, Some(profile_id)).await?+ if let Some(business_profile) = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ processor,+ Some(profile_id),+ )+ .await?{Ok(business_profile)} else {- db.find_business_profile_by_profile_id(processor.get_key_store(), profile_id)+ state+ .accounts_store+ .find_business_profile_by_profile_id(processor.get_key_store(), profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {id: profile_id.get_string_repr().to_owned(),@@ -4538,18 +4542,16 @@ pub async fn payouts_manual_update_core(connector_payout_id,} = req;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InternalServerError).attach_printable("Error while fetching the key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)diff --git a/crates/router/src/core/payouts/helpers.rs b/crates/router/src/core/payouts/helpers.rsindex 9c58fad66b..90d6ff74c7 100644--- a/crates/router/src/core/payouts/helpers.rs+++ b/crates/router/src/core/payouts/helpers.rs@@ -1111,7 +1111,7 @@ pub async fn decide_payout_connector(// Validate and get the business_profile from payout_attemptlet business_profile = core_utils::validate_and_get_business_profile(- state.store.as_ref(),+ state.accounts_store.as_ref(),processor,Some(&payout_attempt.profile_id),)diff --git a/crates/router/src/core/payouts/proxy.rs b/crates/router/src/core/payouts/proxy.rsindex 7424c451fd..d3490b7b03 100644--- a/crates/router/src/core/payouts/proxy.rs+++ b/crates/router/src/core/payouts/proxy.rs@@ -449,7 +449,7 @@ impl ExternalVaultPayout<'_> {)?;let provider = platform.get_provider();let external_vault_mca = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(provider.get_account().get_id(),&vault_connector_id,diff --git a/crates/router/src/core/payouts/validator.rs b/crates/router/src/core/payouts/validator.rsindex 7b884c4eb0..14c9e946e7 100644--- a/crates/router/src/core/payouts/validator.rs+++ b/crates/router/src/core/payouts/validator.rs@@ -185,7 +185,7 @@ pub async fn validate_create_request(req.business_label.as_ref(),platform.get_processor(),req.profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?;let profile_id = business_profile.get_id().to_owned();@@ -240,7 +240,7 @@ pub async fn validate_create_request(req.business_label.as_ref(),platform.get_processor(),req.profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await?;PayoutKillSwitch::ensure_payouts_enabled(state, platform, Some(business_profile.get_id()))diff --git a/crates/router/src/core/pm_auth.rs b/crates/router/src/core/pm_auth.rsindex 2b285c8dd1..d6c17c5a91 100644--- a/crates/router/src/core/pm_auth.rs+++ b/crates/router/src/core/pm_auth.rs@@ -130,7 +130,7 @@ pub async fn create_link_token(#[cfg(feature = "v1")]let merchant_connector_account = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_processor().get_account().get_id(),&selected_config.mca_id,@@ -252,7 +252,7 @@ pub async fn exchange_token_core(#[cfg(feature = "v1")]let merchant_connector_account = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_processor().get_account().get_id(),&config.mca_id,@@ -790,14 +790,13 @@ pub async fn retrieve_payment_method_from_auth_service(auth_token: &payment_methods::BankAccountTokenData,payment_intent: &PaymentIntent,) -> RouterResult<Option<(domain::PaymentMethodData, enums::PaymentMethod)>> {- let db = state.store.as_ref();-let connector = PaymentAuthConnectorData::get_connector_by_name(auth_token.connector_details.connector.as_str(),)?;#[cfg(feature = "v1")]- let mca = db+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(&payment_intent.processor_merchant_id,&auth_token.connector_details.mca_id,diff --git a/crates/router/src/core/profile_acquirer.rs b/crates/router/src/core/profile_acquirer.rsindex 393c41427a..3490403fbb 100644--- a/crates/router/src/core/profile_acquirer.rs+++ b/crates/router/src/core/profile_acquirer.rs@@ -14,11 +14,11 @@ pub async fn create_profile_acquirer(request: profile_acquirer::ProfileAcquirerCreate,processor: domain::Processor,) -> RouterResponse<profile_acquirer::ProfileAcquirerResponse> {- let db = state.store.as_ref();let profile_acquirer_id = common_utils::generate_profile_acquirer_id_of_default_length();let merchant_key_store = processor.get_key_store();- let mut business_profile = db+ let mut business_profile = state+ .accounts_store.find_business_profile_by_profile_id(merchant_key_store, &request.profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -71,7 +71,8 @@ pub async fn create_profile_acquirer(let profile_update = domain::ProfileUpdate::AcquirerConfigBucketUpdate {acquirer_config_map: business_profile.acquirer_config_map.clone(),};- let updated_business_profile = db+ let updated_business_profile = state+ .accounts_store.update_profile_by_profile_id(merchant_key_store, business_profile, profile_update).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -108,10 +109,10 @@ pub async fn update_profile_acquirer_config(request: profile_acquirer::ProfileAcquirerUpdate,processor: domain::Processor,) -> RouterResponse<profile_acquirer::ProfileAcquirerResponse> {- let db = state.store.as_ref();let merchant_key_store = processor.get_key_store();- let mut business_profile = db+ let mut business_profile = state+ .accounts_store.find_business_profile_by_profile_id(merchant_key_store, &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -184,7 +185,8 @@ pub async fn update_profile_acquirer_config(acquirer_config_map: updated_map_for_db_update,};- let updated_business_profile = db+ let updated_business_profile = state+ .accounts_store.update_profile_by_profile_id(merchant_key_store, business_profile, profile_update).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/refunds.rs b/crates/router/src/core/refunds.rsindex 51a1460ff0..7689f634cc 100644--- a/crates/router/src/core/refunds.rs+++ b/crates/router/src/core/refunds.rs@@ -2062,7 +2062,8 @@ pub async fn get_platform_refund_filters(let db = state.store.as_ref();- let merchant_accounts = db+ let merchant_accounts = state+ .accounts_store.list_merchant_accounts_by_organization_id(platform.get_provider().get_account().get_org_id(),)@@ -2075,11 +2076,10 @@ pub async fn get_platform_refund_filters(account.merchant_account_type == common_enums::MerchantAccountType::Connected}) {let merchant_id = connected_account.get_id().clone();- let key_store = db- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -2224,17 +2224,15 @@ pub async fn refund_manual_update(state: SessionState,req: api_models::refunds::RefundManualUpdateRequest,) -> RouterResponse<serde_json::Value> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &req.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&req.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound).attach_printable("Error while fetching the key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&req.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)diff --git a/crates/router/src/core/refunds/surcharge.rs b/crates/router/src/core/refunds/surcharge.rsindex 7095841b33..553963d3b4 100644--- a/crates/router/src/core/refunds/surcharge.rs+++ b/crates/router/src/core/refunds/surcharge.rs@@ -358,7 +358,7 @@ pub async fn complete_from_webhook(};let storage_scheme = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, key_store).await.map(|account| account.storage_scheme)@@ -444,7 +444,7 @@ async fn resolve_interpayments_account() -> RouterResult<helpers::MerchantConnectorAccountType> {let processor = platform.get_processor();let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(processor.get_key_store(), profile_id).await.change_context(errors::ApiErrorResponse::ProfileNotFound {diff --git a/crates/router/src/core/refunds_v2.rs b/crates/router/src/core/refunds_v2.rsindex f40b7e004d..7849cacb5d 100644--- a/crates/router/src/core/refunds_v2.rs+++ b/crates/router/src/core/refunds_v2.rs@@ -146,13 +146,12 @@ pub async fn trigger_refund_to_gateway(diesel_refund::Refund,Option<hyperswitch_masking::Secret<String>>,)> {- let db = &*state.store;-let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?;let storage_scheme = processor.get_account().storage_scheme;- let mca = db+ let mca = state+ .accounts_store.find_merchant_connector_account_by_id(&mca_id, processor.get_key_store()).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -858,8 +857,6 @@ pub async fn sync_refund_with_gateway(diesel_refund::Refund,Option<hyperswitch_masking::Secret<String>>,)> {- let db = &*state.store;-let connector_id = refund.connector.to_string();let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(&state.conf.connectors,@@ -872,7 +869,8 @@ pub async fn sync_refund_with_gateway(let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?;- let mca = db+ let mca = state+ .accounts_store.find_merchant_connector_account_by_id(&mca_id, processor.get_key_store()).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/relay.rs b/crates/router/src/core/relay.rsindex 0558925b30..ee94495fa0 100644--- a/crates/router/src/core/relay.rs+++ b/crates/router/src/core/relay.rs@@ -740,7 +740,8 @@ pub async fn relay<T: RelayInterface>(let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;- let profile = db+ let profile = state+ .accounts_store.find_business_profile_by_merchant_id_profile_id(platform.get_processor().get_key_store(),processor_merchant_id,@@ -752,7 +753,8 @@ pub async fn relay<T: RelayInterface>(})?;#[cfg(feature = "v1")]- let connector_account = db+ let connector_account = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(processor_merchant_id,connector_id,@@ -764,7 +766,8 @@ pub async fn relay<T: RelayInterface>(})?;#[cfg(feature = "v2")]- let connector_account = db+ let connector_account = state+ .accounts_store.find_merchant_connector_account_by_id(connector_id,platform.get_processor().get_key_store(),@@ -828,15 +831,17 @@ pub async fn relay_retrieve(let profile_id_from_auth_layer = profile_id_optional.get_required_value("ProfileId")?;- db.find_business_profile_by_merchant_id_profile_id(- platform.get_processor().get_key_store(),- merchant_id,- &profile_id_from_auth_layer,- )- .await- .change_context(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id_from_auth_layer.get_string_repr().to_owned(),- })?;+ state+ .accounts_store+ .find_business_profile_by_merchant_id_profile_id(+ platform.get_processor().get_key_store(),+ merchant_id,+ &profile_id_from_auth_layer,+ )+ .await+ .change_context(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id_from_auth_layer.get_string_repr().to_owned(),+ })?;let relay_record_result = db.find_relay_by_id(platform.get_processor().get_key_store(), relay_id)@@ -858,7 +863,8 @@ pub async fn relay_retrieve(};#[cfg(feature = "v1")]- let connector_account = db+ let connector_account = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(merchant_id,&relay_record.connector_id,@@ -870,7 +876,8 @@ pub async fn relay_retrieve(})?;#[cfg(feature = "v2")]- let connector_account = db+ let connector_account = state+ .accounts_store.find_merchant_connector_account_by_id(&relay_record.connector_id,platform.get_processor().get_key_store(),@@ -1012,7 +1019,8 @@ async fn process_unreferenced_refund(let connector_id: &id_type::MerchantConnectorAccountId = &request.connector_id;#[cfg(feature = "v1")]- let connector_account = db+ let connector_account = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(processor_merchant_id,connector_id,@@ -1024,7 +1032,8 @@ async fn process_unreferenced_refund(})?;#[cfg(feature = "v2")]- let connector_account = db+ let connector_account = state+ .accounts_store.find_merchant_connector_account_by_id(connector_id,platform.get_processor().get_key_store(),@@ -1195,18 +1204,19 @@ async fn process_relay_unreferenced_refund(})})?;- let db = state.store.as_ref();let merchant_id = platform.get_processor().get_account().get_id();- db.find_business_profile_by_merchant_id_profile_id(- platform.get_processor().get_key_store(),- merchant_id,- profile_id,- )- .await- .change_context(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;+ state+ .accounts_store+ .find_business_profile_by_merchant_id_profile_id(+ platform.get_processor().get_key_store(),+ merchant_id,+ profile_id,+ )+ .await+ .change_context(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;let dimensions = dimension_state::Dimensions::new().with_processor_merchant_id(platform.get_processor().get_processor_merchant_id())@@ -1221,10 +1231,18 @@ async fn process_relay_unreferenced_refund(.with_profile_id(profile_id.clone()).with_currency(request.currency);let min_amount = dimensions- .get_payout_min_amount(db, state.superposition_service.as_ref(), Some(profile_id))+ .get_payout_min_amount(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ Some(profile_id),+ ).await;let max_amount = dimensions- .get_payout_max_amount(db, state.superposition_service.as_ref(), Some(profile_id))+ .get_payout_max_amount(+ state.store.as_ref(),+ state.superposition_service.as_ref(),+ Some(profile_id),+ ).await;request.validate_amount(min_amount, max_amount)diff --git a/crates/router/src/core/revenue_recovery/api.rs b/crates/router/src/core/revenue_recovery/api.rsindex e04f265523..48b8612161 100644--- a/crates/router/src/core/revenue_recovery/api.rs+++ b/crates/router/src/core/revenue_recovery/api.rs@@ -369,7 +369,7 @@ async fn find_connector_account_of_profile(};let connector_account = state- .store+ .accounts_store.find_merchant_connector_account_by_id(merchant_connector_id,platform.get_processor().get_key_store(),diff --git a/crates/router/src/core/revenue_recovery/external_triggers.rs b/crates/router/src/core/revenue_recovery/external_triggers.rsindex 7e8769c4ad..ffc98f51e8 100644--- a/crates/router/src/core/revenue_recovery/external_triggers.rs+++ b/crates/router/src/core/revenue_recovery/external_triggers.rs@@ -1077,11 +1077,11 @@ async fn load_recovery_request_context(state: &SessionState,tracking_data: &pcr::RecoveryRequestTrackingData,) -> error_stack::Result<(Platform, domain::Profile), errors::StorageError> {- let db = &*state.store;+ let db = state.accounts_store.as_ref();let key_store = db.get_merchant_key_store_by_merchant_id(&tracking_data.merchant_id,- &db.get_master_key().to_vec().into(),+ &state.store.get_master_key().to_vec().into(),).await?;let merchant_account = dbdiff --git a/crates/router/src/core/routing.rs b/crates/router/src/core/routing.rsindex 6e91849b61..36a97e6b2e 100644--- a/crates/router/src/core/routing.rs+++ b/crates/router/src/core/routing.rs@@ -189,7 +189,7 @@ pub async fn routing_entry(// that exists without ancestry still beats failing the dashboard entry.let processor = platform.get_processor();match core_utils::validate_and_get_business_profile(- state.store.as_ref(),+ state.accounts_store.as_ref(),processor,Some(&profile_id),)@@ -383,17 +383,19 @@ async fn find_de_record_for_algorithm(authentication_profile_id: Option<common_utils::id_type::ProfileId>,algorithm_id: &common_utils::id_type::RoutingId,) -> RouterResult<Option<(domain::Profile, RoutingAlgorithmRecord)>> {- let db = state.store.as_ref();let processor = platform.get_processor();let candidate_profiles = match authentication_profile_id {- Some(profile_id) => {- core_utils::validate_and_get_business_profile(db, processor, Some(&profile_id))- .await?- .map(|profile| vec![profile])- .unwrap_or_default()- }- None => db+ Some(profile_id) => core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ processor,+ Some(&profile_id),+ )+ .await?+ .map(|profile| vec![profile])+ .unwrap_or_default(),+ None => state+ .accounts_store.list_profile_by_merchant_id(processor.get_key_store(),processor.get_account().get_id(),@@ -706,7 +708,6 @@ async fn build_list_routing_result(de_results: &[routing_types::RoutingDictionaryRecord],profile_ids: Vec<common_utils::id_type::ProfileId>,) -> RouterResult<Vec<routing_types::RoutingDictionaryRecord>> {- let db = state.store.as_ref();let mut list_result: Vec<routing_types::RoutingDictionaryRecord> = vec![];for profile_id in profile_ids.iter() {let by_profile =@@ -715,7 +716,7 @@ async fn build_list_routing_result(let mut hs_result_for_profile: Vec<routing_types::RoutingDictionaryRecord> =hs_results.iter().filter(by_profile).cloned().collect();let business_profile = match core_utils::validate_and_get_business_profile(- db,+ state.accounts_store.as_ref(),platform.get_processor(),Some(profile_id),)@@ -761,23 +762,23 @@ pub async fn create_routing_algorithm_under_profile(transaction_type: enums::TransactionType,) -> RouterResponse<routing_types::RoutingDictionaryRecord> {metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]);- let db = &*state.store;let processor = platform.get_processor();- let business_profile =- core_utils::validate_and_get_business_profile(db, processor, Some(&request.profile_id))- .await?- .get_required_value("Profile")?;+ let business_profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ processor,+ Some(&request.profile_id),+ )+ .await?+ .get_required_value("Profile")?;let processor_merchant_id = processor.get_account().get_id();core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;// Fetching disabled MCAs too: routing configs may reference MCAs that are// temporarily disabled — validation checks connector existence, not activity.- let all_mcas = state- .store- .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(- processor_merchant_id,- business_profile.get_id(),- )+ let all_mcas = state.accounts_store.list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ processor_merchant_id,+ business_profile.get_id(),+ ).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: processor_merchant_id.get_string_repr().to_owned(),@@ -871,10 +872,13 @@ pub async fn create_routing_algorithm_under_profile(}).attach_printable("Profile_id not provided")?;- let business_profile =- core_utils::validate_and_get_business_profile(db, processor, Some(&profile_id))- .await?- .get_required_value("Profile")?;+ let business_profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")?;core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;@@ -1066,10 +1070,13 @@ pub async fn link_routing_config_under_profile(})})?;- let business_profile =- core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id))- .await?- .get_required_value("Profile")?;+ let business_profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")?;utils::when(routing_algorithm.0.algorithm_for != *transaction_type,@@ -1094,7 +1101,7 @@ pub async fn link_routing_config_under_profile()?;admin::ProfileWrapper::new(business_profile).update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(- db,+ &state,key_manager_state,processor.get_key_store(),algorithm_id,@@ -1181,7 +1188,7 @@ pub async fn link_routing_config(};let business_profile = core_utils::validate_and_get_business_profile(- db,+ state.accounts_store.as_ref(),&processor,Some(&routing_algorithm.profile_id),)@@ -1394,7 +1401,7 @@ pub async fn link_routing_config(}helpers::update_business_profile_active_dynamic_algorithm_ref(- db,+ state.accounts_store.as_ref(),processor.get_key_store(),business_profile.clone(),dynamic_routing_ref,@@ -1538,7 +1545,7 @@ pub async fn link_routing_config()?;routing_ref.update_algorithm_id(algorithm_id);helpers::update_profile_active_algorithm_ref(- db,+ &state,processor.get_key_store(),business_profile.clone(),routing_ref,@@ -1611,7 +1618,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id().await?;let business_profile = core_utils::validate_and_get_business_profile(- db,+ state.accounts_store.as_ref(),&processor,Some(&routing_algorithm.0.profile_id),)@@ -1667,7 +1674,7 @@ pub async fn retrieve_routing_algorithm_from_algorithm_id(};let business_profile = core_utils::validate_and_get_business_profile(- db,+ state.accounts_store.as_ref(),&processor,Some(&routing_algorithm.profile_id),)@@ -1714,10 +1721,13 @@ pub async fn unlink_routing_config_under_profile(let db = state.store.as_ref();let key_manager_state = &(&state).into();- let business_profile =- core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id))- .await?- .get_required_value("Profile")?;+ let business_profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")?;let routing_algo_id = match transaction_type {enums::TransactionType::Payment => business_profile.routing_algorithm_id.clone(),@@ -1737,7 +1747,7 @@ pub async fn unlink_routing_config_under_profile(let response = record.0.foreign_into();admin::ProfileWrapper::new(business_profile).update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(- db,+ &state,key_manager_state,processor.get_key_store(),algorithm_id,@@ -1774,8 +1784,12 @@ pub async fn unlink_routing_config(}).attach_printable("Profile_id not provided")?;- let business_profile =- core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id)).await?;+ let business_profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?;match business_profile {Some(business_profile) => {@@ -1875,7 +1889,7 @@ pub async fn unlink_routing_config(let response = record.foreign_into();helpers::update_profile_active_algorithm_ref(- db,+ &state,processor.get_key_store(),business_profile.clone(),routing_algorithm,@@ -1944,11 +1958,14 @@ pub async fn update_default_fallback_routing(updated_list_of_connectors: Vec<routing_types::RoutableConnectorChoice>,) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {metrics::ROUTING_UPDATE_CONFIG.add(1, &[]);- let db = state.store.as_ref();let key_manager_state = &(&state).into();- let profile = core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id))- .await?- .get_required_value("Profile")?;+ let profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")?;let profile_wrapper = admin::ProfileWrapper::new(profile);let default_list_of_connectors =profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;@@ -1992,7 +2009,7 @@ pub async fn update_default_fallback_routing()?;profile_wrapper.update_default_fallback_routing_of_connectors_under_profile(- db,+ state.accounts_store.as_ref(),&updated_list_of_connectors,key_manager_state,processor.get_key_store(),@@ -2065,10 +2082,13 @@ pub async fn retrieve_default_fallback_algorithm_for_profile(profile_id: common_utils::id_type::ProfileId,) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]);- let db = state.store.as_ref();- let profile = core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id))- .await?- .get_required_value("Profile")?;+ let profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")?;let connectors_choice = admin::ProfileWrapper::new(profile).get_default_fallback_list_of_connector_under_profile()?;@@ -2115,10 +2135,13 @@ pub async fn retrieve_routing_config_under_profile(metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(1, &[]);let db = state.store.as_ref();- let business_profile =- core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id))- .await?- .get_required_value("Profile")?;+ let business_profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")?;let record = db.list_routing_algorithm_metadata_by_profile_id(@@ -2158,7 +2181,7 @@ pub async fn retrieve_linked_routing_config(// Get business profileslet business_profiles = if let Some(profile_id) = query_params.profile_id {core_utils::validate_and_get_business_profile(- db,+ state.accounts_store.as_ref(),platform.get_processor(),Some(&profile_id),)@@ -2169,7 +2192,8 @@ pub async fn retrieve_linked_routing_config(id: profile_id.get_string_repr().to_owned(),})?} else {- let business_profile = db+ let business_profile = state+ .accounts_store.list_profile_by_merchant_id(merchant_key_store, merchant_id).await.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;@@ -2389,7 +2413,8 @@ pub async fn retrieve_default_routing_config_for_profiles(metrics::ROUTING_RETRIEVE_CONFIG_FOR_PROFILE.add(1, &[]);let db = state.store.as_ref();- let all_profiles = db+ let all_profiles = state+ .accounts_store.list_profile_by_merchant_id(processor.get_key_store(), processor.get_account().get_id()).await.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)@@ -2437,13 +2462,16 @@ pub async fn update_default_routing_config_for_profile(let db = state.store.as_ref();- let business_profile =- core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id))- .await?- .get_required_value("Profile")- .change_context(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;+ let business_profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")+ .change_context(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;let default_config = helpers::get_merchant_default_config(db,business_profile.get_id().get_string_repr(),@@ -2504,14 +2532,16 @@ pub async fn update_default_routing_config_for_profile(let profile_update = domain::ProfileUpdate::DefaultRoutingFallbackUpdate {default_fallback_routing: Some(default_fallback_routing),};- db.update_profile_by_profile_id(- processor.get_key_store(),- business_profile.clone(),- profile_update,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update default_fallback_routing in business profile")?;+ state+ .accounts_store+ .update_profile_by_profile_id(+ processor.get_key_store(),+ business_profile.clone(),+ profile_update,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update default_fallback_routing in business profile")?;metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]);Ok(service_api::ApplicationResponse::Json(@@ -2538,16 +2568,18 @@ pub async fn create_specific_dynamic_routing(("algorithm_type", dynamic_routing_type.to_string())),);- let db = state.store.as_ref();let processor = platform.get_processor();- let business_profile: domain::Profile =- core_utils::validate_and_get_business_profile(db, processor, Some(&profile_id))- .await?- .get_required_value("Profile")- .change_context(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;+ let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")+ .change_context(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile.dynamic_routing_algorithm@@ -2576,13 +2608,13 @@ pub async fn create_specific_dynamic_routing(}routing::DynamicRoutingFeatures::None => {// disable specific dynamic routing for the requested profile- helpers::disable_dynamic_routing_algorithm(+ Box::pin(helpers::disable_dynamic_routing_algorithm(&state,processor.get_key_store().inner().clone(),business_profile,dynamic_routing_algo_ref,dynamic_routing_type,- )+ )).await}}@@ -2599,7 +2631,6 @@ pub async fn configure_dynamic_routing_volume_split(1,router_env::metric_attributes!(("profile_id", profile_id.clone())),);- let db = state.store.as_ref();utils::when(routing_info.split > crate::consts::DYNAMIC_ROUTING_MAX_VOLUME,@@ -2610,13 +2641,16 @@ pub async fn configure_dynamic_routing_volume_split(},)?;- let business_profile: domain::Profile =- core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id))- .await?- .get_required_value("Profile")- .change_context(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;+ let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")+ .change_context(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;let mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile.dynamic_routing_algorithm@@ -2632,7 +2666,7 @@ pub async fn configure_dynamic_routing_volume_split(dynamic_routing_algo_ref.update_volume_split(Some(routing_info.split));helpers::update_business_profile_active_dynamic_algorithm_ref(- db,+ state.accounts_store.as_ref(),processor.get_key_store(),business_profile.clone(),dynamic_routing_algo_ref.clone(),@@ -2648,15 +2682,16 @@ pub async fn retrieve_dynamic_routing_volume_split(processor: domain::Processor,profile_id: common_utils::id_type::ProfileId,) -> RouterResponse<routing_types::RoutingVolumeSplitResponse> {- let db = state.store.as_ref();-- let business_profile: domain::Profile =- core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id))- .await?- .get_required_value("Profile")- .change_context(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;+ let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")+ .change_context(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile.dynamic_routing_algorithm@@ -2689,13 +2724,16 @@ pub async fn contract_based_dynamic_routing_setup(let db = state.store.as_ref();let processor = platform.get_processor();- let business_profile: domain::Profile =- core_utils::validate_and_get_business_profile(db, processor, Some(&profile_id))- .await?- .get_required_value("Profile")- .change_context(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;+ let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")+ .change_context(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;let mut dynamic_routing_algo_ref: Option<routing_types::DynamicRoutingAlgorithmRef> =business_profile@@ -2736,13 +2774,13 @@ pub async fn contract_based_dynamic_routing_setup(.clone().get_required_value("dynamic_routing_algo_ref").attach_printable("Failed to get dynamic_routing_algo_ref")?;- return helpers::disable_dynamic_routing_algorithm(+ return Box::pin(helpers::disable_dynamic_routing_algorithm(&state,processor.get_key_store().inner().clone(),business_profile,algorithm,routing_types::DynamicRoutingType::ContractBasedRouting,- )+ )).await;}@@ -2806,7 +2844,7 @@ pub async fn contract_based_dynamic_routing_setup(// validate the contained mca_idsif let Some(info_vec) = &config.label_info {helpers::validate_contract_based_label_info(- db,+ &state,processor.get_account().get_id(),&profile_id,info_vec,@@ -2821,7 +2859,7 @@ pub async fn contract_based_dynamic_routing_setup(.attach_printable("Unable to insert record in routing algorithm table")?;helpers::update_business_profile_active_dynamic_algorithm_ref(- db,+ state.accounts_store.as_ref(),processor.get_key_store(),business_profile,final_algorithm,@@ -3013,17 +3051,15 @@ async fn get_merchant_account(hyperswitch_domain_models::platform::MerchantKeyStore,domain::MerchantAccount,)> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -3166,13 +3202,16 @@ async fn migrate_rules_for_profile(let state = state.clone();let db = state.store.as_ref();- let business_profile =- core_utils::validate_and_get_business_profile(db, &processor, Some(&profile_id))- .await?- .get_required_value("Profile")- .change_context(errors::ApiErrorResponse::ProfileNotFound {- id: profile_id.get_string_repr().to_owned(),- })?;+ let business_profile = core_utils::validate_and_get_business_profile(+ state.accounts_store.as_ref(),+ &processor,+ Some(&profile_id),+ )+ .await?+ .get_required_value("Profile")+ .change_context(errors::ApiErrorResponse::ProfileNotFound {+ id: profile_id.get_string_repr().to_owned(),+ })?;// Provision the scope, with its ancestry, before migrating any rule into it — otherwise the// rules route but the dashboard handoff returns "merchant not found".diff --git a/crates/router/src/core/routing/helpers.rs b/crates/router/src/core/routing/helpers.rsindex 55e7806d00..f07e21cc96 100644--- a/crates/router/src/core/routing/helpers.rs+++ b/crates/router/src/core/routing/helpers.rs@@ -47,7 +47,7 @@ use crate::{errors::{self, RouterResult},payments::routing::utils::{self as routing_utils, DecisionEngineApiHandler},},- db::StorageInterface,+ db::{AccountsStorageInterface, StorageInterface},routes::SessionState,services,types::{domain, storage},@@ -210,14 +210,16 @@ pub async fn update_merchant_active_algorithm_ref(};let db = &*state.store;- db.update_specific_fields_in_merchant(- &key_store.merchant_id,- merchant_account_update,- key_store,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update routing algorithm ref in merchant account")?;+ state+ .accounts_store+ .update_specific_fields_in_merchant(+ &key_store.merchant_id,+ merchant_account_update,+ key_store,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update routing algorithm ref in merchant account")?;cache::redact_from_redis_and_publish(db, [config_key]).await@@ -229,12 +231,13 @@ pub async fn update_merchant_active_algorithm_ref(#[cfg(feature = "v1")]pub async fn update_profile_active_algorithm_ref(- db: &dyn StorageInterface,+ state: &SessionState,merchant_key_store: &domain::MerchantKeyStore,current_business_profile: domain::Profile,algorithm_id: routing_types::RoutingAlgorithmRef,transaction_type: &storage::enums::TransactionType,) -> RouterResult<()> {+ let db = state.store.as_ref();let ref_val = algorithm_id.encode_to_value().change_context(errors::ApiErrorResponse::InternalServerError)@@ -258,14 +261,16 @@ pub async fn update_profile_active_algorithm_ref(three_ds_decision_rule_algorithm,};- db.update_profile_by_profile_id(- merchant_key_store,- current_business_profile,- business_profile_update,- )- .await- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable("Failed to update routing algorithm ref in business profile")?;+ state+ .accounts_store+ .update_profile_by_profile_id(+ merchant_key_store,+ current_business_profile,+ business_profile_update,+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to update routing algorithm ref in business profile")?;// Invalidate the routing cache for Payments and Payouts transaction typesif !transaction_type.is_three_ds_authentication() {@@ -288,7 +293,7 @@ pub async fn update_profile_active_algorithm_ref(#[cfg(feature = "v1")]pub async fn update_business_profile_active_dynamic_algorithm_ref(- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,merchant_key_store: &domain::MerchantKeyStore,current_business_profile: domain::Profile,dynamic_routing_algorithm_ref: routing_types::DynamicRoutingAlgorithmRef,@@ -472,18 +477,17 @@ impl RoutingAlgorithmHelpers<'_> {/// not an error), so it maps to `InternalServerError` rather than a 404.#[cfg(all(feature = "v1", feature = "dynamic_routing"))]pub async fn validate_contract_based_label_info(- db: &dyn StorageInterface,+ state: &SessionState,merchant_id: &id_type::MerchantId,profile_id: &id_type::ProfileId,label_info: &[routing_types::LabelInformation],) -> RouterResult<()> {// Fetching disabled MCAs too: a contract config may reference a temporarily disabled// MCA — validation checks connector existence and label, not activity.- let all_mcas = db- .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(- merchant_id,- profile_id,- )+ let all_mcas = state.accounts_store.list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(+ merchant_id,+ profile_id,+ ).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable(@@ -535,9 +539,7 @@ pub async fn validate_connectors_in_routing_config() -> RouterResult<()> {// Fetching disabled MCAs too: routing configs may reference MCAs that are// temporarily disabled — validation checks connector existence, not activity.- let all_mcas = state- .store- .list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(merchant_id, profile_id)+ let all_mcas = state.accounts_store.list_merchant_connector_accounts_without_encrypted_including_disabled_by_merchant_id_profile_id(merchant_id, profile_id).await.change_context(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: merchant_id.get_string_repr().to_owned(),@@ -2009,7 +2011,7 @@ pub async fn disable_dynamic_routing_algorithm(.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;let response = record.foreign_into();update_business_profile_active_dynamic_algorithm_ref(- db,+ state.accounts_store.as_ref(),&key_store,business_profile,dynamic_routing_algorithm,@@ -2091,7 +2093,7 @@ where{//Check for payloadif let Some(payload) = payload {- return create_specific_dynamic_routing_setup(+ return Box::pin(create_specific_dynamic_routing_setup(state,platform,business_profile,@@ -2099,19 +2101,19 @@ wheredynamic_routing_algo_ref,dynamic_routing_type,payload,- )+ )).await;}// Algorithm wasn't created yetlet Some(mut algo_type) = algo_type else {- return default_specific_dynamic_routing_setup(+ return Box::pin(default_specific_dynamic_routing_setup(state,platform,business_profile,feature_to_enable,dynamic_routing_algo_ref,dynamic_routing_type,- )+ )).await;};@@ -2121,14 +2123,14 @@ where.get_algorithm_id_with_timestamp().algorithm_idelse {- return default_specific_dynamic_routing_setup(+ return Box::pin(default_specific_dynamic_routing_setup(state,platform,business_profile,feature_to_enable,dynamic_routing_algo_ref,dynamic_routing_type,- )+ )).await;};let db = state.store.as_ref();@@ -2147,7 +2149,7 @@ where*algo_type_enabled_features = feature_to_enable;dynamic_routing_algo_ref.update_enabled_features(dynamic_routing_type, feature_to_enable);update_business_profile_active_dynamic_algorithm_ref(- db,+ state.accounts_store.as_ref(),platform.get_processor().get_key_store(),business_profile,dynamic_routing_algo_ref.clone(),@@ -2274,7 +2276,7 @@ pub async fn default_specific_dynamic_routing_setup(dynamic_routing_type,);update_business_profile_active_dynamic_algorithm_ref(- db,+ state.accounts_store.as_ref(),platform.get_processor().get_key_store(),business_profile,dynamic_routing_algo_ref,@@ -2402,7 +2404,7 @@ pub async fn create_specific_dynamic_routing_setup(dynamic_routing_algo_ref.update_feature(feature_to_enable, dynamic_routing_type);update_business_profile_active_dynamic_algorithm_ref(- db,+ state.accounts_store.as_ref(),platform.get_processor().get_key_store(),business_profile,dynamic_routing_algo_ref,diff --git a/crates/router/src/core/superposition_sdk_config.rs b/crates/router/src/core/superposition_sdk_config.rsindex c4711d6d65..4a88144132 100644--- a/crates/router/src/core/superposition_sdk_config.rs+++ b/crates/router/src/core/superposition_sdk_config.rs@@ -142,7 +142,6 @@ pub async fn get_profile_superposition_sdk_config(profile_id: String,) -> RouterResponse<SuperPositionConfigResponse> {let merchant_account = platform.get_processor().get_account();- let db = &*state.store;let profile_id_typed =common_utils::id_type::ProfileId::try_from(std::borrow::Cow::from(profile_id.clone()))@@ -150,7 +149,8 @@ pub async fn get_profile_superposition_sdk_config(field_name: "profile_id".into(),})?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&profile_id_typed,@@ -160,7 +160,8 @@ pub async fn get_profile_superposition_sdk_config(id: profile_id.to_owned(),})?;- let mcas = db+ let mcas = state+ .accounts_store.list_enabled_merchant_connector_accounts_without_encrypted_by_merchant_id_profile_id(platform.get_processor().get_account().get_id(),&profile_id_typed,@@ -374,7 +375,8 @@ pub async fn get_superposition_sdk_config(},)?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {diff --git a/crates/router/src/core/unified_authentication_service.rs b/crates/router/src/core/unified_authentication_service.rsindex 385572f188..b5c74040ad 100644--- a/crates/router/src/core/unified_authentication_service.rs+++ b/crates/router/src/core/unified_authentication_service.rs@@ -715,7 +715,6 @@ pub async fn authentication_create_core(profile_id_from_auth_layer: Option<common_utils::id_type::ProfileId>,req: AuthenticationCreateRequest,) -> RouterResponse<AuthenticationResponse> {- let db = &*state.store;let processor_merchant_account = platform.get_processor().get_account();let processor_merchant_id = processor_merchant_account.get_id();let key_manager_state = (&state).into();@@ -726,7 +725,7 @@ pub async fn authentication_create_core(req.profile_id.as_ref().or(profile_id_from_auth_layer.as_ref()),- db,+ state.accounts_store.as_ref(),).await?;core_utils::validate_profile_id_from_auth_layer(profile_id_from_auth_layer, &business_profile)?;@@ -1089,7 +1088,7 @@ pub async fn authentication_eligibility_core(None,platform.get_processor(),Some(&authentication.profile_id),- db,+ state.accounts_store.as_ref(),).await?;let profile_id = business_profile.get_id().to_owned();@@ -1392,7 +1391,8 @@ pub async fn authentication_authenticate_core(let profile_id = authentication.profile_id.clone();- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id).await.to_not_found_response(ApiErrorResponse::ProfileNotFound {@@ -2105,7 +2105,8 @@ pub async fn authentication_sync_core(let profile_id = authentication.profile_id.clone();- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id).await.to_not_found_response(ApiErrorResponse::ProfileNotFound {@@ -2411,7 +2412,8 @@ pub async fn authentication_post_sync_core(ensure_not_terminal_status(authentication.trans_status.clone())?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&authentication.profile_id,@@ -2547,7 +2549,7 @@ pub async fn authentication_session_core(let mut session_tokens = Vec::new();let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&authentication.profile_id,@@ -2595,7 +2597,7 @@ pub async fn get_session_token_for_click_to_pay(let key_manager_state = &state.into();let merchant_connector_account = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(processor.get_account().get_id(),&click_to_pay_mca_id,diff --git a/crates/router/src/core/unified_authentication_service/utils.rs b/crates/router/src/core/unified_authentication_service/utils.rsindex 4083b53a72..1e63413b7b 100644--- a/crates/router/src/core/unified_authentication_service/utils.rs+++ b/crates/router/src/core/unified_authentication_service/utils.rs@@ -530,7 +530,7 @@ pub async fn get_auth_multi_token_from_external_vault<F, Req>(let external_vault_mca_id = external_vault_details.vault_connector_id.clone();let merchant_connector_account_details = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_processor().get_account().get_id(),&external_vault_mca_id,diff --git a/crates/router/src/core/user.rs b/crates/router/src/core/user.rsindex b2554b8b5e..9273d4a428 100644--- a/crates/router/src/core/user.rs+++ b/crates/router/src/core/user.rs@@ -150,17 +150,15 @@ pub async fn get_active_user_details(.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve role information")?;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id, &key_store_master_key).await;let version = if let Ok(merchant_key_store) = merchant_key_store {let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id, &merchant_key_store).await;@@ -449,17 +447,15 @@ pub async fn get_user_merchant_details(state: SessionState,user_from_token: auth::UserFromToken,) -> UserResponse<UserMerchantDetailsResponse> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id, &key_store_master_key).await.change_context(UserErrors::InternalServerError)?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id, &key_store).await.change_context(UserErrors::InternalServerError)?;@@ -520,7 +516,7 @@ pub async fn change_password(#[cfg(not(feature = "email"))]{state- .store+ .accounts_store.delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(&user_from_token.user_id,&user_from_token.merchant_id,@@ -781,18 +777,19 @@ async fn handle_invitation(match req_role_info.get_entity_type() {EntityType::Tenant | EntityType::Organization => {}EntityType::Merchant | EntityType::Profile => {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id,&merchant_key_store,@@ -1651,14 +1648,13 @@ pub async fn create_internal_user(|| Err(UserErrors::InvalidRoleId),)?;+ let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id(+ consts::user_role::INTERNAL_USER_MERCHANT_ID,+ );+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &common_utils::id_type::MerchantId::get_internal_user_merchant_id(- consts::user_role::INTERNAL_USER_MERCHANT_ID,- ),- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&internal_merchant_id, &key_store_master_key).await.map_err(|e| {if e.current_context().is_db_not_found() {@@ -1679,12 +1675,8 @@ pub async fn create_internal_user(.attach_printable("Operation allowed only for the default tenant");}- let internal_merchant_id = common_utils::id_type::MerchantId::get_internal_user_merchant_id(- consts::user_role::INTERNAL_USER_MERCHANT_ID,- );-let internal_merchant = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&internal_merchant_id, &key_store).await.map_err(|e| {@@ -1736,7 +1728,7 @@ pub async fn create_tenant_user(request: user_api::CreateTenantUserRequest,) -> UserResponse<()> {let (merchant_id, org_id) = state- .store+ .accounts_store.list_merchant_and_org_ids(1, None).await.change_context(UserErrors::InternalServerError)@@ -1806,14 +1798,13 @@ pub async fn create_platform_account(let organization_id = organization.get_organization_id();state- .track_accounts_query(|db| {- db.update_organization_by_org_id(- &organization_id,- diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {- platform_merchant_id: merchant_account.get_id().clone(),- },- )- })+ .accounts_store+ .update_organization_by_org_id(+ &organization_id,+ diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {+ platform_merchant_id: merchant_account.get_id().clone(),+ },+ ).await.change_context(UserErrors::InternalServerError)?;@@ -1859,7 +1850,8 @@ pub async fn create_org_merchant_for_user() -> UserResponse<()> {let db_organization = ForeignFrom::foreign_from(req.clone());let org: diesel_models::organization::Organization = state- .track_accounts_query(|db| db.insert_organization(db_organization))+ .accounts_store+ .insert_organization(db_organization).await.change_context(UserErrors::InternalServerError)?;let default_product_type = consts::user::DEFAULT_PRODUCT_TYPE;@@ -1962,7 +1954,8 @@ pub async fn list_user_roles_details(.collect::<HashSet<_>>();let org_name = state- .track_accounts_query(|db| db.find_organization_by_org_id(&user_from_token.org_id))+ .accounts_store+ .find_organization_by_org_id(&user_from_token.org_id).await.change_context(UserErrors::InternalServerError).attach_printable("Org id not found")?@@ -2019,7 +2012,7 @@ pub async fn list_user_roles_details()?;let merchant_map = state- .store+ .accounts_store.list_multiple_merchant_accounts(merchant_ids).await.change_context(UserErrors::InternalServerError)@@ -2035,18 +2028,19 @@ pub async fn list_user_roles_details(let profile_map = futures::future::try_join_all(merchant_profile_ids.iter().map(|merchant_profile_id| async {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&merchant_profile_id.0,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;state- .store+ .accounts_store.find_business_profile_by_profile_id(&merchant_key_store, &merchant_profile_id.1).await.change_context(UserErrors::InternalServerError)@@ -3217,7 +3211,7 @@ pub async fn list_orgs_for_user(}let orgs = match role_info.get_entity_type() {EntityType::Tenant => state- .store+ .accounts_store.list_merchant_and_org_ids(consts::user::ORG_LIST_LIMIT_FOR_TENANT, None).await.change_context(UserErrors::InternalServerError)?@@ -3249,7 +3243,7 @@ pub async fn list_orgs_for_user(let resp = futures::future::try_join_all(orgs.iter()- .map(|org_id| state.track_accounts_query(|db| db.find_organization_by_org_id(org_id))),+ .map(|org_id| state.accounts_store.find_organization_by_org_id(org_id)),).await.change_context(UserErrors::InternalServerError)?@@ -3293,7 +3287,7 @@ pub async fn list_merchants_for_user_in_org(let merchant_accounts = match role_info.get_entity_type() {EntityType::Tenant | EntityType::Organization => state- .store+ .accounts_store.list_merchant_accounts_by_organization_id(&user_from_token.org_id).await.change_context(UserErrors::InternalServerError)?,@@ -3323,7 +3317,7 @@ pub async fn list_merchants_for_user_in_org(.collect();state- .store+ .accounts_store.list_multiple_merchant_accounts(merchant_ids).await.change_context(UserErrors::InternalServerError)?@@ -3363,17 +3357,15 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(.await.change_context(UserErrors::InternalServerError)?;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id, &key_store_master_key).await.change_context(UserErrors::InternalServerError)?;let profiles = match role_info.get_entity_type() {EntityType::Tenant | EntityType::Organization | EntityType::Merchant => state- .store+ .accounts_store.list_profile_by_merchant_id(&key_store, &user_from_token.merchant_id).await.change_context(UserErrors::InternalServerError)?,@@ -3402,7 +3394,7 @@ pub async fn list_profiles_for_user_in_org_and_merchant_account(futures::future::try_join_all(profile_ids.iter().map(|profile_id| {state- .store+ .accounts_store.find_business_profile_by_profile_id(&key_store, profile_id)})).await@@ -3462,7 +3454,7 @@ pub async fn switch_org_for_user(let (merchant_id, profile_id, role_id) = match role_info.get_entity_type() {EntityType::Tenant => {let merchant_id = state- .store+ .accounts_store.list_merchant_accounts_by_organization_id(&request.org_id).await.change_context(UserErrors::InternalServerError)@@ -3473,17 +3465,15 @@ pub async fn switch_org_for_user(.get_id().to_owned();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.change_context(UserErrors::InternalServerError)?;let profile_id = state- .store+ .accounts_store.list_profile_by_merchant_id(&key_store, &merchant_id).await.change_context(UserErrors::InternalServerError)?@@ -3602,23 +3592,21 @@ pub async fn switch_merchant_for_user_in_org(// Check if the role is internal and handle separatelylet (org_id, merchant_id, profile_id, role_id) = if role_info.is_internal() {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &request.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&request.merchant_id, &key_store_master_key).await.to_not_found_response(UserErrors::MerchantIdNotFound)?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&request.merchant_id, &merchant_key_store).await.to_not_found_response(UserErrors::MerchantIdNotFound)?;let profile_id = state- .store+ .accounts_store.list_profile_by_merchant_id(&merchant_key_store, &request.merchant_id).await.change_context(UserErrors::InternalServerError)@@ -3639,17 +3627,18 @@ pub async fn switch_merchant_for_user_in_org(// Match based on the other entity typesmatch role_info.get_entity_type() {EntityType::Tenant | EntityType::Organization => {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&request.merchant_id,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await.to_not_found_response(UserErrors::MerchantIdNotFound)?;let merchant_id = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&request.merchant_id, &merchant_key_store).await.change_context(UserErrors::MerchantIdNotFound)?@@ -3663,7 +3652,7 @@ pub async fn switch_merchant_for_user_in_org(})?;let profile_id = state- .store+ .accounts_store.list_profile_by_merchant_id(&merchant_key_store, &merchant_id).await.change_context(UserErrors::InternalServerError)@@ -3797,18 +3786,19 @@ pub async fn switch_profile_for_user_in_org_and_merchant(let (profile_id, role_id) = match role_info.get_entity_type() {EntityType::Tenant | EntityType::Organization | EntityType::Merchant => {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;let profile_id = state- .store+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&merchant_key_store,&user_from_token.merchant_id,@@ -3925,19 +3915,17 @@ pub async fn clone_connector(},)?;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id, &key_store_master_key).await.to_not_found_response(UserErrors::InvalidCloneConnectorOperation("Merchant account not found".to_string(),))?;let source_mca = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(&user_from_token.merchant_id,&request.source_mca_id,@@ -3955,7 +3943,7 @@ pub async fn clone_connector(})?;state- .store+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&user_from_token.merchant_id,@@ -3990,7 +3978,7 @@ pub async fn clone_connector(.await?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id, &key_store).await.to_not_found_response(UserErrors::InvalidCloneConnectorOperation(@@ -4033,7 +4021,7 @@ pub async fn issue_embedded_token(.get_id().clone();state- .store+ .accounts_store.find_business_profile_by_merchant_id_profile_id(processor.get_key_store(),processor.get_account().get_id(),diff --git a/crates/router/src/core/user/dashboard_metadata.rs b/crates/router/src/core/user/dashboard_metadata.rsindex f84503f210..8b3b4066df 100644--- a/crates/router/src/core/user/dashboard_metadata.rs+++ b/crates/router/src/core/user/dashboard_metadata.rs@@ -758,12 +758,10 @@ pub async fn backfill_metadata(user: &UserFromToken,key: &DBEnum,) -> UserResult<Option<DashboardMetadata>> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&user.merchant_id, &key_store_master_key).await.change_context(UserErrors::InternalServerError)?;@@ -872,7 +870,7 @@ pub async fn get_merchant_connector_account_by_name(#[cfg(feature = "v1")]{state- .store+ .accounts_store.find_merchant_connector_account_by_merchant_id_connector_name(merchant_id,connector_name,diff --git a/crates/router/src/core/user/sample_data.rs b/crates/router/src/core/user/sample_data.rsindex 55abc92afb..46178d2272 100644--- a/crates/router/src/core/user/sample_data.rs+++ b/crates/router/src/core/user/sample_data.rs@@ -28,12 +28,10 @@ pub async fn generate_sample_data_for_user().await?;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id, &key_store_master_key).await.change_context(SampleDataError::InternalServerError).attach_printable("Not able to fetch merchant key store")?; // If not able to fetch merchant key store for any reason, this should be an internal server error@@ -96,12 +94,10 @@ pub async fn delete_sample_data_for_user() -> SampleDataApiResponse<()> {let merchant_id_del = user_from_token.merchant_id;let key_manager_state = &(&state).into();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id_del,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id_del, &key_store_master_key).await.change_context(SampleDataError::InternalServerError).attach_printable("Not able to fetch merchant key store")?; // If not able to fetch merchant key store for any reason, this should be an internal server errordiff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rsindex f09a3a8a16..ff08f9e772 100644--- a/crates/router/src/core/user_role.rs+++ b/crates/router/src/core/user_role.rs@@ -764,7 +764,7 @@ pub async fn delete_user_role(// If user has no more role associated with him then deleting userif remaining_roles.is_empty() {let _ = state- .store+ .accounts_store.delete_all_metadata_by_user_id(user_from_db.get_user_id()).await.inspect_err(|e| {@@ -1067,7 +1067,8 @@ pub async fn list_invitations_for_user(let org_name_map = futures::future::try_join_all(org_ids.into_iter().map(|org_id| async {let org_name = state- .track_accounts_query(|db| db.find_organization_by_org_id(&org_id))+ .accounts_store+ .find_organization_by_org_id(&org_id).await.change_context(UserErrors::InternalServerError)?.get_organization_name()@@ -1080,7 +1081,7 @@ pub async fn list_invitations_for_user(.collect::<HashMap<_, _>>();let merchant_name_map = state- .store+ .accounts_store.list_multiple_merchant_accounts(merchant_ids).await.change_context(UserErrors::InternalServerError)?@@ -1100,13 +1101,13 @@ pub async fn list_invitations_for_user(let profile_name_map = futures::future::try_join_all(profile_ids_with_merchant_ids.iter().map(|(profile_id, merchant_id)| async {let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(merchant_id, master_key).await.change_context(UserErrors::InternalServerError)?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(&merchant_key_store, profile_id).await.change_context(UserErrors::InternalServerError)?;diff --git a/crates/router/src/core/user_role/role.rs b/crates/router/src/core/user_role/role.rsindex 0cd3b03c37..d22a104607 100644--- a/crates/router/src/core/user_role/role.rs+++ b/crates/router/src/core/user_role/role.rs@@ -116,18 +116,16 @@ pub async fn create_role(let role_name = RoleName::new(req.role_name)?;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id, &key_store_master_key).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id, &merchant_key_store).await.to_not_found_response(UserErrors::MerchantIdNotFound)?;@@ -249,18 +247,16 @@ pub async fn create_role_v2(let permission_groups =utils::user_role::parent_group_info_request_to_permission_groups(&req.parent_groups)?;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id, &key_store_master_key).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id, &merchant_key_store).await.to_not_found_response(UserErrors::MerchantIdNotFound)?;@@ -504,18 +500,19 @@ pub async fn update_role(let merchant_product_type = match role_info.get_entity_type() {EntityType::Tenant | EntityType::Organization => None,EntityType::Merchant | EntityType::Profile => {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id,&merchant_key_store,@@ -636,18 +633,19 @@ pub async fn list_roles_with_info(match entity_type {EntityType::Tenant | EntityType::Organization => {}EntityType::Merchant | EntityType::Profile => {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id,&merchant_key_store,@@ -813,18 +811,19 @@ pub async fn list_roles_at_entity_level(match req.entity_type {EntityType::Tenant | EntityType::Organization => {}EntityType::Merchant | EntityType::Profile => {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;let product_type = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id,&merchant_key_store,diff --git a/crates/router/src/core/utils.rs b/crates/router/src/core/utils.rsindex 9fb5869c62..db704d7773 100644--- a/crates/router/src/core/utils.rs+++ b/crates/router/src/core/utils.rs@@ -68,7 +68,7 @@ use crate::{payment_methods,payments::PaymentData,},- db::StorageInterface,+ db::AccountsStorageInterface,routes::{metrics::MerchantMode, SessionState},types::{self, api, domain,@@ -928,18 +928,16 @@ pub async fn build_platform_from_refund_core(state: &SessionState,refund_core: &diesel_refund::RefundCoreWorkflow,) -> RouterResult<domain::Platform> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let provider_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &refund_core.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&refund_core.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound).attach_printable("Error while fetching the key store for provider merchant")?;let provider_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&refund_core.merchant_id, &provider_key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)@@ -950,18 +948,16 @@ pub async fn build_platform_from_refund_core(.as_ref().unwrap_or(&refund_core.merchant_id);+ let key_store_master_key = state.store.get_master_key().to_vec().into();let processor_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- processor_merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(processor_merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound).attach_printable("Error while fetching the key store for processor merchant")?;let processor_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(processor_merchant_id, &processor_key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)@@ -2344,7 +2340,7 @@ pub fn get_payout_connector_customer_id(/// Validate whether the profile_id exists and is associated with the merchant_idpub async fn validate_and_get_business_profile(- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,processor: &domain::Processor,profile_id: Option<&common_utils::id_type::ProfileId>,) -> RouterResult<Option<domain::Profile>> {@@ -2413,7 +2409,7 @@ pub async fn get_profile_from_business_details(business_label: Option<&String>,processor: &domain::Processor,request_profile_id: Option<&common_utils::id_type::ProfileId>,- db: &dyn StorageInterface,+ db: &dyn AccountsStorageInterface,) -> RouterResult<domain::Profile> {match request_profile_id.or(processor.get_account().default_profile.as_ref()) {Some(profile_id) => dbdiff --git a/crates/router/src/core/verification/utils.rs b/crates/router/src/core/verification/utils.rsindex 81f36046c1..a56cd46075 100644--- a/crates/router/src/core/verification/utils.rs+++ b/crates/router/src/core/verification/utils.rs@@ -24,18 +24,16 @@ pub async fn get_apple_pay_merchant_connector_account((domain::MerchantKeyStore, domain::MerchantConnectorAccount),errors::ApiErrorResponse,> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;#[cfg(feature = "v1")]let merchant_connector_account = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(merchant_id,merchant_connector_id,@@ -46,7 +44,7 @@ pub async fn get_apple_pay_merchant_connector_account(#[cfg(feature = "v2")]let merchant_connector_account = state- .store+ .accounts_store.find_merchant_connector_account_by_id(merchant_connector_id, &key_store).await.change_context(errors::ApiErrorResponse::ResourceIdNotFound)?;@@ -119,7 +117,7 @@ pub async fn add_domain_to_apple_pay_merchant_connector_account(};let merchant_connector_id = merchant_connector_account.get_id();state- .store+ .accounts_store.update_merchant_connector_account(merchant_connector_account,updated_mca.foreign_into(),diff --git a/crates/router/src/core/webhooks/incoming.rs b/crates/router/src/core/webhooks/incoming.rsindex faa72beb43..e091cd2021 100644--- a/crates/router/src/core/webhooks/incoming.rs+++ b/crates/router/src/core/webhooks/incoming.rs@@ -580,7 +580,7 @@ async fn process_webhook_business_logic(let profile_id = &merchant_connector_account.profile_id;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -3554,20 +3554,22 @@ async fn fetch_optional_mca_and_connector(),errors::ApiErrorResponse,> {- let db = &state.store;if connector_name_or_mca_id.starts_with("mca_") {#[cfg(feature = "v1")]- let mca = db+ let merchant_connector_id = common_utils::id_type::MerchantConnectorAccountId::wrap(+ connector_name_or_mca_id.to_owned(),+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Error while converting MerchanConnectorAccountId from string+ ",+ )?;+ #[cfg(feature = "v1")]+ let mca = state+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_processor().get_account().get_id(),- &common_utils::id_type::MerchantConnectorAccountId::wrap(- connector_name_or_mca_id.to_owned(),- )- .change_context(errors::ApiErrorResponse::InternalServerError)- .attach_printable(- "Error while converting MerchanConnectorAccountId from string- ",- )?,+ &merchant_connector_id,platform.get_processor().get_key_store(),).await@@ -3582,7 +3584,6 @@ async fn fetch_optional_mca_and_connector(let mca: domain::MerchantConnectorAccount = {let _ = merchant_account;let _ = key_store;- let _ = db;todo!()};diff --git a/crates/router/src/core/webhooks/incoming_v2.rs b/crates/router/src/core/webhooks/incoming_v2.rsindex ad74d852d2..69b2c7bd1c 100644--- a/crates/router/src/core/webhooks/incoming_v2.rs+++ b/crates/router/src/core/webhooks/incoming_v2.rs@@ -823,8 +823,8 @@ async fn fetch_mca_and_connector(),errors::ApiErrorResponse,> {- let db = &state.store;- let mca = db+ let mca = state+ .accounts_store.find_merchant_connector_account_by_id(connector_id, key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {diff --git a/crates/router/src/core/webhooks/network_tokenization_incoming.rs b/crates/router/src/core/webhooks/network_tokenization_incoming.rsindex 2895f7ed98..a40ad80908 100644--- a/crates/router/src/core/webhooks/network_tokenization_incoming.rs+++ b/crates/router/src/core/webhooks/network_tokenization_incoming.rs@@ -453,19 +453,16 @@ pub async fn fetch_merchant_account_for_network_token_webhooks(state: &SessionState,merchant_id: &id_type::MerchantId,) -> RouterResult<domain::Platform> {- let db = &*state.store;-- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::Unauthorized).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, &key_store).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/webhooks/outgoing.rs b/crates/router/src/core/webhooks/outgoing.rsindex 728198bfb5..05cc33a895 100644--- a/crates/router/src/core/webhooks/outgoing.rs+++ b/crates/router/src/core/webhooks/outgoing.rs@@ -152,7 +152,7 @@ async fn get_surcharge_webhook_event(merchant_surcharge_connector_id: common_utils::id_type::MerchantConnectorAccountId,) -> CustomResult<Option<types::WebhookPayload>, errors::ApiErrorResponse> {let merchant_surcharge_connector = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(platform.get_provider().get_account().get_id(),&merchant_surcharge_connector_id,@@ -672,7 +672,7 @@ async fn trigger_webhook_to_connector(};let mca_result = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(&provider_merchant_id,merchant_connector_id,@@ -797,7 +797,7 @@ async fn update_payment_attempt_from_webhook_response() {if event.event_type == enums::EventType::SurchargePaymentSucceeded {let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, merchant_key_store).await;diff --git a/crates/router/src/core/webhooks/recovery_incoming.rs b/crates/router/src/core/webhooks/recovery_incoming.rsindex b4e8883273..8edbefcb90 100644--- a/crates/router/src/core/webhooks/recovery_incoming.rs+++ b/crates/router/src/core/webhooks/recovery_incoming.rs@@ -31,7 +31,7 @@ use crate::{payments::{self, helpers},revenue_recovery::retry_stats,},- db::{errors::RevenueRecoveryError, StorageInterface},+ db::errors::RevenueRecoveryError,routes::{app::ReqState, metrics, SessionState},services::{self,@@ -1091,8 +1091,12 @@ impl RevenueRecoveryAttempt {)})?;- let db = &*state.store;- db.find_merchant_connector_account_by_id(&payment_merchant_connector_account_id, key_store)+ state+ .accounts_store+ .find_merchant_connector_account_by_id(+ &payment_merchant_connector_account_id,+ key_store,+ ).await.change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound {diff --git a/crates/router/src/core/webhooks/utils.rs b/crates/router/src/core/webhooks/utils.rsindex 9834c7aacb..2023b87b61 100644--- a/crates/router/src/core/webhooks/utils.rs+++ b/crates/router/src/core/webhooks/utils.rs@@ -428,7 +428,7 @@ async fn get_default_profile_for_platform_merchant(.attach_printable("Platform merchant does not have a default profile configured")?;state- .store+ .accounts_store.find_business_profile_by_profile_id(provider.get_key_store(), profile_id).await.change_context(errors::ApiErrorResponse::InternalServerError)@@ -449,7 +449,7 @@ async fn get_default_profile_for_platform_merchant(})?;let profiles = state- .store+ .accounts_store.list_profile_by_merchant_id(provider.get_key_store(), provider.get_account().get_id()).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/core/webhooks/webhook_events.rs b/crates/router/src/core/webhooks/webhook_events.rsindex 6fdba991ea..31c3621d64 100644--- a/crates/router/src/core/webhooks/webhook_events.rs+++ b/crates/router/src/core/webhooks/webhook_events.rs@@ -35,14 +35,16 @@ pub async fn list_initial_delivery_attempts(// to them. Events are filtered by `initiator_merchant_id = merchant_id`// (with a fallback on `merchant_id` column for rows created before the// initiator column existed).- let key_store = store+ let key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&merchant_id, master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;// Validate the profile_id if provided.if let Some(ref profile_id) = profile_id {- store+ state+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store, &merchant_id, profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -270,7 +272,8 @@ pub async fn list_delivery_attempts(// scoped by the unique `initial_attempt_id`, so no merchant filter is// required in the query — but we verify ownership below to prevent a// merchant from reading another merchant's event chain.- let key_store = store+ let key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&merchant_id, master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -298,7 +301,8 @@ pub async fn list_delivery_attempts(.first().and_then(|event| event.business_profile_id.clone()){- Some(business_profile_id) => store+ Some(business_profile_id) => state+ .accounts_store.find_business_profile_by_profile_id(&key_store, &business_profile_id).await.inspect_err(|error| {@@ -342,7 +346,8 @@ pub async fn retry_delivery_attempt(// The calling merchant is the webhook recipient, so their keystore was used// to encrypt the original event. Use it for decryption.- let key_store = store+ let key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&merchant_id, master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -382,7 +387,8 @@ pub async fn retry_delivery_attempt(.get_required_value("business_profile_id").change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to read business profile ID from event to retry")?;- let business_profile = store+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(&key_store, &business_profile_id).await.change_context(errors::ApiErrorResponse::InternalServerError)diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex b97f3162f5..731ef4db6b 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -53,15 +53,18 @@ use diesel_models::{use error_stack::ResultExt;#[cfg(feature = "payouts")]use hyperswitch_domain_models::payouts::{- payout_attempt::PayoutAttemptInterface, payouts::PayoutsInterface,+ payout_attempt::TrackedPayoutAttemptInterface, payouts::TrackedPayoutsInterface,};use hyperswitch_domain_models::{- authentication::AuthenticationInterface,- card_issuer::CardIssuersInterface,- cards_info::CardsInfoInterface,+ authentication::TrackedAuthenticationInterface,+ card_issuer::TrackedCardIssuersInterface,+ cards_info::TrackedCardsInfoInterface,master_key::MasterKeyInterface,- payment_methods::PaymentMethodInterface,- payments::{payment_attempt::PaymentAttemptInterface, payment_intent::PaymentIntentInterface},+ payment_methods::TrackedPaymentMethodInterface,+ payments::{+ payment_attempt::TrackedPaymentAttemptInterface,+ payment_intent::TrackedPaymentIntentInterface,+ },};#[cfg(not(feature = "payouts"))]use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};@@ -76,7 +79,10 @@ use storage_impl::{};pub use self::kafka_store::KafkaStore;-use self::{fraud_check::FraudCheckInterface, organization::OrganizationInterface};+use self::{+ fraud_check::FraudCheckInterface,+ organization::{OrganizationInterface, TrackedOrganizationInterface},+};pub use crate::{core::errors::{self, ProcessTrackerError},errors::CustomResult,@@ -103,62 +109,56 @@ pub trait StorageInterface:Send+ Sync+ dyn_clone::DynClone- + address::AddressInterface- + api_keys::ApiKeyInterface- + blocklist_lookup::BlocklistLookupInterface- + configs::ConfigInterface<Error = StorageError>- + capture::CaptureInterface- + customers::CustomerInterface<Error = StorageError>- + dashboard_metadata::DashboardMetadataInterface- + dispute::DisputeInterface- + client_secret::ClientSecretInterface- + events::EventInterface- + file::FileMetadataInterface- + FraudCheckInterface- + locker_mock_up::LockerMockUpInterface- + mandate::MandateInterface- + merchant_account::MerchantAccountInterface<Error = StorageError>+ + address::TrackedAddressInterface+ + api_keys::TrackedApiKeyInterface+ + blocklist_lookup::TrackedBlocklistLookupInterface+ + hyperswitch_domain_models::configs::TrackedConfigInterface<Error = StorageError>+ + capture::TrackedCaptureInterface+ + hyperswitch_domain_models::customer::TrackedCustomerInterface<Error = StorageError>+ + dispute::TrackedDisputeInterface+ + client_secret::TrackedClientSecretInterface+ + events::TrackedEventInterface+ + file::TrackedFileMetadataInterface+ + fraud_check::TrackedFraudCheckInterface+ + locker_mock_up::TrackedLockerMockUpInterface+ + mandate::TrackedMandateInterface+ merchant_connector_account::ConnectorAccessToken- + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>- + PaymentAttemptInterface<Error = StorageError>- + PaymentIntentInterface<Error = StorageError>- + PaymentMethodInterface<Error = StorageError>- + analytics_report::AnalyticsReportInterface- + blocklist::BlocklistInterface- + blocklist_fingerprint::BlocklistFingerprintInterface- + batch_blocklist_job::BatchBlocklistJobInterface- + CardIssuersInterface<Error = StorageError>- + dynamic_routing_stats::DynamicRoutingStatsInterface+ + TrackedPaymentAttemptInterface<Error = StorageError>+ + TrackedPaymentIntentInterface<Error = StorageError>+ + TrackedPaymentMethodInterface<Error = StorageError>+ + analytics_report::TrackedAnalyticsReportInterface+ + blocklist::TrackedBlocklistInterface+ + blocklist_fingerprint::TrackedBlocklistFingerprintInterface+ + batch_blocklist_job::TrackedBatchBlocklistJobInterface+ + TrackedCardIssuersInterface<Error = StorageError>+ + dynamic_routing_stats::TrackedDynamicRoutingStatsInterface+ scheduler::SchedulerInterface- + PayoutAttemptInterface<Error = StorageError>- + PayoutsInterface<Error = StorageError>- + refund::RefundInterface- + reverse_lookup::ReverseLookupInterface- + CardsInfoInterface<Error = StorageError>- + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>- + hierarchical_resource::HierarchicalResourceInterface<Error = StorageError>+ + TrackedPayoutAttemptInterface<Error = StorageError>+ + TrackedPayoutsInterface<Error = StorageError>+ + refund::TrackedRefundInterface+ + reverse_lookup::TrackedReverseLookupInterface+ + TrackedCardsInfoInterface<Error = StorageError>+ MasterKeyInterface- + payment_link::PaymentLinkInterface+ + payment_link::TrackedPaymentLinkInterface+ RedisConnInterface+ CacheInterface+ RequestIdStore- + business_profile::ProfileInterface<Error = StorageError>- + routing_algorithm::RoutingAlgorithmInterface- + gsm::GsmInterface- + unified_translations::UnifiedTranslationsInterface- + authorization::AuthorizationInterface- + user::sample_data::BatchSampleDataInterface- + health_check::HealthCheckDbInterface- + user_authentication_method::UserAuthenticationMethodInterface- + AuthenticationInterface<Error = StorageError>- + generic_link::GenericLinkInterface- + relay::RelayInterface- + user::theme::ThemeInterface- + payment_method_session::PaymentMethodsSessionInterface- + tokenization::TokenizationInterface- + callback_mapper::CallbackMapperInterface- + storage_impl::subscription::SubscriptionInterface<Error = StorageError>- + storage_impl::invoice::InvoiceInterface<Error = StorageError>+ + routing_algorithm::TrackedRoutingAlgorithmInterface+ + gsm::TrackedGsmInterface+ + unified_translations::TrackedUnifiedTranslationsInterface+ + authorization::TrackedAuthorizationInterface+ + user::sample_data::TrackedBatchSampleDataInterface+ + health_check::TrackedHealthCheckDbInterface+ + user_authentication_method::TrackedUserAuthenticationMethodInterface+ + TrackedAuthenticationInterface<Error = StorageError>+ + generic_link::TrackedGenericLinkInterface+ + relay::TrackedRelayInterface+ + user::theme::TrackedThemeInterface+ + payment_method_session::TrackedPaymentMethodsSessionInterface+ + tokenization::TrackedTokenizationInterface+ + callback_mapper::TrackedCallbackMapperInterface+ + hyperswitch_domain_models::subscription::TrackedSubscriptionInterface<Error = StorageError>+ + hyperswitch_domain_models::invoice::TrackedInvoiceInterface<Error = StorageError>+ 'static{fn get_scheduler_db(&self) -> Box<dyn scheduler::SchedulerInterface>;@@ -217,16 +217,17 @@ pub trait AccountsStorageInterface:Send+ Sync+ dyn_clone::DynClone- + OrganizationInterface- + merchant_account::MerchantAccountInterface<Error = StorageError>- + business_profile::ProfileInterface<Error = StorageError>- + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>- + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>- + hierarchical_resource::HierarchicalResourceInterface<Error = StorageError>- + dashboard_metadata::DashboardMetadataInterface+ + TrackedOrganizationInterface+ + merchant_account::TrackedMerchantAccountInterface<Error = StorageError>+ + business_profile::TrackedProfileInterface<Error = StorageError>+ + merchant_connector_account::TrackedMerchantConnectorAccountInterface<Error = StorageError>+ + merchant_key_store::TrackedMerchantKeyStoreInterface<Error = StorageError>+ + hierarchical_resource::TrackedHierarchicalResourceInterface<Error = StorageError>+ + dashboard_metadata::TrackedDashboardMetadataInterface+ RequestIdStore+ 'static{+ fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState);}#[cfg(not(feature = "deja"))]@@ -235,16 +236,17 @@ pub trait AccountsStorageInterface:Send+ Sync+ dyn_clone::DynClone- + OrganizationInterface- + merchant_account::MerchantAccountInterface<Error = StorageError>- + business_profile::ProfileInterface<Error = StorageError>- + merchant_connector_account::MerchantConnectorAccountInterface<Error = StorageError>- + merchant_key_store::MerchantKeyStoreInterface<Error = StorageError>- + hierarchical_resource::HierarchicalResourceInterface<Error = StorageError>- + dashboard_metadata::DashboardMetadataInterface+ + TrackedOrganizationInterface+ + merchant_account::TrackedMerchantAccountInterface<Error = StorageError>+ + business_profile::TrackedProfileInterface<Error = StorageError>+ + merchant_connector_account::TrackedMerchantConnectorAccountInterface<Error = StorageError>+ + merchant_key_store::TrackedMerchantKeyStoreInterface<Error = StorageError>+ + hierarchical_resource::TrackedHierarchicalResourceInterface<Error = StorageError>+ + dashboard_metadata::TrackedDashboardMetadataInterface+ RequestIdStore+ 'static{+ fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState);}pub trait CommonStorageInterface:@@ -299,7 +301,11 @@ impl GlobalStorageInterface for Store {}}-impl AccountsStorageInterface for Store {}+impl AccountsStorageInterface for Store {+ fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState) {+ StorageInterface::set_key_manager_state(self, key_manager_state);+ }+}#[async_trait::async_trait]impl StorageInterface for MockDb {@@ -338,7 +344,11 @@ impl GlobalStorageInterface for MockDb {}}-impl AccountsStorageInterface for MockDb {}+impl AccountsStorageInterface for MockDb {+ fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState) {+ StorageInterface::set_key_manager_state(self, key_manager_state);+ }+}impl CommonStorageInterface for MockDb {fn get_global_storage_interface(&self) -> Box<dyn GlobalStorageInterface> {@@ -527,13 +537,13 @@ impl OrganizationInterface for KafkaStore {&self,organization: OrganizationNew,) -> CustomResult<Organization, StorageError> {- self.diesel_store.insert_organization(organization).await+ OrganizationInterface::insert_organization(&self.diesel_store, organization).await}async fn find_organization_by_org_id(&self,org_id: &id_type::OrganizationId,) -> CustomResult<Organization, StorageError> {- self.diesel_store.find_organization_by_org_id(org_id).await+ OrganizationInterface::find_organization_by_org_id(&self.diesel_store, org_id).await}async fn update_organization_by_org_id(@@ -541,8 +551,7 @@ impl OrganizationInterface for KafkaStore {org_id: &id_type::OrganizationId,update: OrganizationUpdate,) -> CustomResult<Organization, StorageError> {- self.diesel_store- .update_organization_by_org_id(org_id, update)+ OrganizationInterface::update_organization_by_org_id(&self.diesel_store, org_id, update).await}}diff --git a/crates/router/src/db/address.rs b/crates/router/src/db/address.rsindex a542fa99ee..6071d3792a 100644--- a/crates/router/src/db/address.rs+++ b/crates/router/src/db/address.rs@@ -14,6 +14,7 @@ use crate::{},};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait AddressInterfacewherediff --git a/crates/router/src/db/analytics_report.rs b/crates/router/src/db/analytics_report.rsindex 3e087f8734..fdde035b30 100644--- a/crates/router/src/db/analytics_report.rs+++ b/crates/router/src/db/analytics_report.rs@@ -5,6 +5,7 @@ pub use olap::*;/// Reports need the `olap` feature; without it the interface is empty.#[cfg(not(feature = "olap"))]+#[router_derive::track_async_interface]pub trait AnalyticsReportInterface {}#[cfg(not(feature = "olap"))]@@ -38,6 +39,7 @@ mod olap {}}+ #[router_derive::track_async_interface]#[async_trait::async_trait]pub trait AnalyticsReportInterface {/// Runs `query` on the read replica as one read-only cursor, so Postgres scans once, and sends@@ -99,9 +101,14 @@ mod olap {fetch_timeout: std::time::Duration,pages: tokio::sync::mpsc::Sender<Vec<ReportRow>>,) -> CustomResult<(), errors::StorageError> {- self.diesel_store- .stream_analytics_report(query, page_size, fetch_timeout, pages)- .await+ AnalyticsReportInterface::stream_analytics_report(+ &self.diesel_store,+ query,+ page_size,+ fetch_timeout,+ pages,+ )+ .await}}diff --git a/crates/router/src/db/api_keys.rs b/crates/router/src/db/api_keys.rsindex e234a86f2c..37d41b5647 100644--- a/crates/router/src/db/api_keys.rs+++ b/crates/router/src/db/api_keys.rs@@ -10,6 +10,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait ApiKeyInterface {async fn insert_api_key(diff --git a/crates/router/src/db/authorization.rs b/crates/router/src/db/authorization.rsindex a71fa24d48..19289b9209 100644--- a/crates/router/src/db/authorization.rs+++ b/crates/router/src/db/authorization.rs@@ -9,6 +9,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait AuthorizationInterface {async fn insert_authorization(diff --git a/crates/router/src/db/batch_blocklist_job.rs b/crates/router/src/db/batch_blocklist_job.rsindex 67bd71e8a2..fe9b845de3 100644--- a/crates/router/src/db/batch_blocklist_job.rs+++ b/crates/router/src/db/batch_blocklist_job.rs@@ -80,6 +80,7 @@ fn apply_profile_clone_target_update(Ok(())}+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait BatchBlocklistJobInterface {async fn insert_batch_blocklist_job(@@ -453,7 +454,7 @@ impl BatchBlocklistJobInterface for KafkaStore {&self,new: storage::BatchBlocklistJobNew,) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {- self.diesel_store.insert_batch_blocklist_job(new).await+ BatchBlocklistJobInterface::insert_batch_blocklist_job(&self.diesel_store, new).await}#[instrument(skip_all)]@@ -462,9 +463,12 @@ impl BatchBlocklistJobInterface for KafkaStore {id: &str,merchant_id: &str,) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {- self.diesel_store- .find_batch_blocklist_job_by_id_merchant_id(id, merchant_id)- .await+ BatchBlocklistJobInterface::find_batch_blocklist_job_by_id_merchant_id(+ &self.diesel_store,+ id,+ merchant_id,+ )+ .await}#[instrument(skip_all)]@@ -476,15 +480,15 @@ impl BatchBlocklistJobInterface for KafkaStore {limit: i64,offset: i64,) -> CustomResult<Vec<storage::BatchBlocklistJob>, errors::StorageError> {- self.diesel_store- .list_batch_blocklist_jobs_by_merchant_id(- merchant_id,- profile_id,- job_type,- limit,- offset,- )- .await+ BatchBlocklistJobInterface::list_batch_blocklist_jobs_by_merchant_id(+ &self.diesel_store,+ merchant_id,+ profile_id,+ job_type,+ limit,+ offset,+ )+ .await}#[instrument(skip_all)]@@ -494,9 +498,13 @@ impl BatchBlocklistJobInterface for KafkaStore {merchant_id: &str,update: storage::BatchBlocklistJobUpdate,) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {- self.diesel_store- .update_batch_blocklist_job_by_id_merchant_id(id, merchant_id, update)- .await+ BatchBlocklistJobInterface::update_batch_blocklist_job_by_id_merchant_id(+ &self.diesel_store,+ id,+ merchant_id,+ update,+ )+ .await}async fn update_profile_clone_job_target(@@ -506,9 +514,14 @@ impl BatchBlocklistJobInterface for KafkaStore {profile_id: &common_utils::id_type::ProfileId,update: storage::BlocklistProfileCloneTargetUpdate,) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {- self.diesel_store- .update_profile_clone_job_target(id, merchant_id, profile_id, update)- .await+ BatchBlocklistJobInterface::update_profile_clone_job_target(+ &self.diesel_store,+ id,+ merchant_id,+ profile_id,+ update,+ )+ .await}#[instrument(skip_all)]@@ -518,8 +531,12 @@ impl BatchBlocklistJobInterface for KafkaStore {profile_id: Option<&common_utils::id_type::ProfileId>,job_type: Option<common_enums::BatchBlocklistJobType>,) -> CustomResult<usize, errors::StorageError> {- self.diesel_store- .count_batch_blocklist_jobs_by_merchant_id(merchant_id, profile_id, job_type)- .await+ BatchBlocklistJobInterface::count_batch_blocklist_jobs_by_merchant_id(+ &self.diesel_store,+ merchant_id,+ profile_id,+ job_type,+ )+ .await}}diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rsindex 8fb1ba16c3..74b52f7c54 100644--- a/crates/router/src/db/blocklist.rs+++ b/crates/router/src/db/blocklist.rs@@ -10,6 +10,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait BlocklistInterface {async fn insert_blocklist_entry(@@ -1238,7 +1239,7 @@ impl BlocklistInterface for KafkaStore {&self,pm_blocklist: storage::BlocklistNew,) -> CustomResult<storage::Blocklist, errors::StorageError> {- self.diesel_store.insert_blocklist_entry(pm_blocklist).await+ BlocklistInterface::insert_blocklist_entry(&self.diesel_store, pm_blocklist).await}#[instrument(skip_all)]@@ -1249,8 +1250,7 @@ impl BlocklistInterface for KafkaStore {profile_id: &common_utils::id_type::ProfileId,fingerprint_id: &str,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .list_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_id(+ BlocklistInterface::list_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_id(&self.diesel_store,processor_merchant_id,transaction_type,profile_id,@@ -1266,13 +1266,13 @@ impl BlocklistInterface for KafkaStore {transaction_type: common_enums::BlocklistTransactionType,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {- self.diesel_store- .find_blocklist_entry_by_processor_merchant_id_fingerprint_id(- processor_merchant_id,- transaction_type,- fingerprint_id,- )- .await+ BlocklistInterface::find_blocklist_entry_by_processor_merchant_id_fingerprint_id(+ &self.diesel_store,+ processor_merchant_id,+ transaction_type,+ fingerprint_id,+ )+ .await}#[instrument(skip_all)]@@ -1283,14 +1283,14 @@ impl BlocklistInterface for KafkaStore {profile_id: &common_utils::id_type::ProfileId,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {- self.diesel_store- .find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(- processor_merchant_id,- transaction_type,- profile_id,- fingerprint_id,- )- .await+ BlocklistInterface::find_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ &self.diesel_store,+ processor_merchant_id,+ transaction_type,+ profile_id,+ fingerprint_id,+ )+ .await}#[instrument(skip_all)]@@ -1301,8 +1301,7 @@ impl BlocklistInterface for KafkaStore {profile_id: &common_utils::id_type::ProfileId,fingerprint_ids: Vec<String>,) -> CustomResult<Option<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .find_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_ids(+ BlocklistInterface::find_blocklist_entries_by_processor_merchant_id_profile_id_fingerprint_ids(&self.diesel_store,processor_merchant_id,transaction_type,profile_id,@@ -1319,14 +1318,14 @@ impl BlocklistInterface for KafkaStore {profile_id: &common_utils::id_type::ProfileId,card_bins: Vec<String>,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(- processor_merchant_id,- transaction_type,- profile_id,- card_bins,- )- .await+ BlocklistInterface::list_blocklist_entries_by_processor_merchant_id_profile_id_card_bins(+ &self.diesel_store,+ processor_merchant_id,+ transaction_type,+ profile_id,+ card_bins,+ )+ .await}#[instrument(skip_all)]@@ -1336,13 +1335,13 @@ impl BlocklistInterface for KafkaStore {transaction_type: common_enums::BlocklistTransactionType,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {- self.diesel_store- .delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(- processor_merchant_id,- transaction_type,- fingerprint_id,- )- .await+ BlocklistInterface::delete_blocklist_entry_by_processor_merchant_id_fingerprint_id(+ &self.diesel_store,+ processor_merchant_id,+ transaction_type,+ fingerprint_id,+ )+ .await}#[instrument(skip_all)]@@ -1354,15 +1353,15 @@ impl BlocklistInterface for KafkaStore {limit: i64,offset: i64,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .list_blocklist_entries_by_processor_merchant_id_data_kind(- processor_merchant_id,- transaction_type,- data_kind,- limit,- offset,- )- .await+ BlocklistInterface::list_blocklist_entries_by_processor_merchant_id_data_kind(+ &self.diesel_store,+ processor_merchant_id,+ transaction_type,+ data_kind,+ limit,+ offset,+ )+ .await}#[instrument(skip_all)]@@ -1373,8 +1372,7 @@ impl BlocklistInterface for KafkaStore {profile_id: &common_utils::id_type::ProfileId,fingerprint_id: &str,) -> CustomResult<storage::Blocklist, errors::StorageError> {- self.diesel_store- .delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(+ BlocklistInterface::delete_blocklist_entry_by_processor_merchant_id_profile_id_fingerprint_id(&self.diesel_store,processor_merchant_id,transaction_type,profile_id,@@ -1393,16 +1391,16 @@ impl BlocklistInterface for KafkaStore {limit: i64,offset: i64,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(- processor_merchant_id,- transaction_type,- profile_id,- data_kind,- limit,- offset,- )- .await+ BlocklistInterface::list_blocklist_entries_by_processor_merchant_id_profile_id_data_kind(+ &self.diesel_store,+ processor_merchant_id,+ transaction_type,+ profile_id,+ data_kind,+ limit,+ offset,+ )+ .await}#[instrument(skip_all)]@@ -1415,8 +1413,7 @@ impl BlocklistInterface for KafkaStore {snapshot_at: time::PrimitiveDateTime,limit: i64,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(+ BlocklistInterface::list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(&self.diesel_store,processor_merchant_id,transaction_type,profile_id,@@ -1437,8 +1434,7 @@ impl BlocklistInterface for KafkaStore {snapshot_at: time::PrimitiveDateTime,limit: i64,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(+ BlocklistInterface::list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(&self.diesel_store,merchant_id,transaction_type,profile_id,@@ -1458,8 +1454,7 @@ impl BlocklistInterface for KafkaStore {snapshot_at: time::PrimitiveDateTime,limit: i64,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id_all_types(+ BlocklistInterface::list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id_all_types(&self.diesel_store,processor_merchant_id,profile_id,after_fingerprint_id,@@ -1478,8 +1473,7 @@ impl BlocklistInterface for KafkaStore {snapshot_at: time::PrimitiveDateTime,limit: i64,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id_all_types(+ BlocklistInterface::list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id_all_types(&self.diesel_store,merchant_id,profile_id,after_fingerprint_id,@@ -1497,8 +1491,7 @@ impl BlocklistInterface for KafkaStore {profile_id: Option<&common_utils::id_type::ProfileId>,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError> {- self.diesel_store- .get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(+ BlocklistInterface::get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(&self.diesel_store,processor_merchant_id,transaction_type,profile_id,@@ -1514,13 +1507,13 @@ impl BlocklistInterface for KafkaStore {transaction_type: common_enums::BlocklistTransactionType,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<usize, errors::StorageError> {- self.diesel_store- .get_blocklist_entries_count_by_processor_merchant_id_data_kind(- processor_merchant_id,- transaction_type,- data_kind,- )- .await+ BlocklistInterface::get_blocklist_entries_count_by_processor_merchant_id_data_kind(+ &self.diesel_store,+ processor_merchant_id,+ transaction_type,+ data_kind,+ )+ .await}#[instrument(skip_all)]@@ -1531,7 +1524,7 @@ impl BlocklistInterface for KafkaStore {profile_id: &common_utils::id_type::ProfileId,data_kind: common_enums::BlocklistDataKind,) -> CustomResult<Vec<(i32, i64)>, errors::StorageError> {- self.diesel_store.count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(+ BlocklistInterface::count_blocklist_entries_by_fingerprint_length_processor_merchant_id_profile_id_data_kind(&self.diesel_store,processor_merchant_id,transaction_type,profile_id,@@ -1546,12 +1539,12 @@ impl BlocklistInterface for KafkaStore {processor_merchant_id: &common_utils::id_type::MerchantId,transaction_type: common_enums::BlocklistTransactionType,) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {- self.diesel_store- .list_blocklist_entries_by_processor_merchant_id(- processor_merchant_id,- transaction_type,- )- .await+ BlocklistInterface::list_blocklist_entries_by_processor_merchant_id(+ &self.diesel_store,+ processor_merchant_id,+ transaction_type,+ )+ .await}#[instrument(skip_all)]@@ -1559,8 +1552,6 @@ impl BlocklistInterface for KafkaStore {&self,entries: Vec<storage::BlocklistNew>,) -> CustomResult<usize, errors::StorageError> {- self.diesel_store- .bulk_insert_blocklist_entries(entries)- .await+ BlocklistInterface::bulk_insert_blocklist_entries(&self.diesel_store, entries).await}}diff --git a/crates/router/src/db/blocklist_fingerprint.rs b/crates/router/src/db/blocklist_fingerprint.rsindex a1f0728602..821af91337 100644--- a/crates/router/src/db/blocklist_fingerprint.rs+++ b/crates/router/src/db/blocklist_fingerprint.rs@@ -10,6 +10,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait BlocklistFingerprintInterface {async fn insert_blocklist_fingerprint_entry(@@ -80,9 +81,11 @@ impl BlocklistFingerprintInterface for KafkaStore {&self,pm_fingerprint_new: storage::BlocklistFingerprintNew,) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {- self.diesel_store- .insert_blocklist_fingerprint_entry(pm_fingerprint_new)- .await+ BlocklistFingerprintInterface::insert_blocklist_fingerprint_entry(+ &self.diesel_store,+ pm_fingerprint_new,+ )+ .await}#[instrument(skip_all)]@@ -91,8 +94,11 @@ impl BlocklistFingerprintInterface for KafkaStore {merchant_id: &common_utils::id_type::MerchantId,fingerprint: &str,) -> CustomResult<storage::BlocklistFingerprint, errors::StorageError> {- self.diesel_store- .find_blocklist_fingerprint_by_merchant_id_fingerprint_id(merchant_id, fingerprint)- .await+ BlocklistFingerprintInterface::find_blocklist_fingerprint_by_merchant_id_fingerprint_id(+ &self.diesel_store,+ merchant_id,+ fingerprint,+ )+ .await}}diff --git a/crates/router/src/db/blocklist_lookup.rs b/crates/router/src/db/blocklist_lookup.rsindex 383e1b9e06..f145adda31 100644--- a/crates/router/src/db/blocklist_lookup.rs+++ b/crates/router/src/db/blocklist_lookup.rs@@ -10,6 +10,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait BlocklistLookupInterface {async fn insert_blocklist_lookup_entry(@@ -103,9 +104,11 @@ impl BlocklistLookupInterface for KafkaStore {&self,blocklist_lookup_entry: storage::BlocklistLookupNew,) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {- self.diesel_store- .insert_blocklist_lookup_entry(blocklist_lookup_entry)- .await+ BlocklistLookupInterface::insert_blocklist_lookup_entry(+ &self.diesel_store,+ blocklist_lookup_entry,+ )+ .await}#[instrument(skip_all)]@@ -114,9 +117,12 @@ impl BlocklistLookupInterface for KafkaStore {merchant_id: &common_utils::id_type::MerchantId,fingerprint: &str,) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {- self.diesel_store- .find_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint)- .await+ BlocklistLookupInterface::find_blocklist_lookup_entry_by_merchant_id_fingerprint(+ &self.diesel_store,+ merchant_id,+ fingerprint,+ )+ .await}#[instrument(skip_all)]@@ -125,8 +131,11 @@ impl BlocklistLookupInterface for KafkaStore {merchant_id: &common_utils::id_type::MerchantId,fingerprint: &str,) -> CustomResult<storage::BlocklistLookup, errors::StorageError> {- self.diesel_store- .delete_blocklist_lookup_entry_by_merchant_id_fingerprint(merchant_id, fingerprint)- .await+ BlocklistLookupInterface::delete_blocklist_lookup_entry_by_merchant_id_fingerprint(+ &self.diesel_store,+ merchant_id,+ fingerprint,+ )+ .await}}diff --git a/crates/router/src/db/business_profile.rs b/crates/router/src/db/business_profile.rsindex ecd8b75610..b81118ed4a 100644--- a/crates/router/src/db/business_profile.rs+++ b/crates/router/src/db/business_profile.rs@@ -1,4 +1,4 @@pub use hyperswitch_domain_models::{- business_profile::{self, ProfileInterface},+ business_profile::{self, ProfileInterface, TrackedProfileInterface},errors::api_error_response,};diff --git a/crates/router/src/db/callback_mapper.rs b/crates/router/src/db/callback_mapper.rsindex 8b34a09003..12d7c693c4 100644--- a/crates/router/src/db/callback_mapper.rs+++ b/crates/router/src/db/callback_mapper.rs@@ -10,6 +10,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait CallbackMapperInterface {async fn insert_call_back_mapper(diff --git a/crates/router/src/db/capture.rs b/crates/router/src/db/capture.rsindex d19f89d628..ff0d98d39f 100644--- a/crates/router/src/db/capture.rs+++ b/crates/router/src/db/capture.rs@@ -6,6 +6,7 @@ use crate::{types::storage::{self as types, enums},};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait CaptureInterface {async fn insert_capture(diff --git a/crates/router/src/db/client_secret.rs b/crates/router/src/db/client_secret.rsindex bed6ef8f4a..12cbe457ae 100644--- a/crates/router/src/db/client_secret.rs+++ b/crates/router/src/db/client_secret.rs@@ -19,6 +19,7 @@ use crate::core::errors::{self, CustomResult};use crate::types::storage::client_secret::{ClientSecretType, ClientSecretTypeNew};use crate::{db::MockDb, services::Store};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait ClientSecretInterface {#[cfg(feature = "v2")]@@ -121,7 +122,7 @@ impl ClientSecretInterface for Store {&self,id: &str,) -> CustomResult<ClientSecretType, errors::StorageError> {- let client_secret = self.get_client_secret(id).await?;+ let client_secret = ClientSecretInterface::get_client_secret(self, id).await?;let redis_id_key = client_secret.id.generate_redis_key();let secret_key = client_secret.generate_secret_key();diff --git a/crates/router/src/db/dashboard_metadata.rs b/crates/router/src/db/dashboard_metadata.rsindex 4a3aa04f8c..cc4576c7b3 100644--- a/crates/router/src/db/dashboard_metadata.rs+++ b/crates/router/src/db/dashboard_metadata.rs@@ -2,14 +2,14 @@ use common_utils::id_type;use diesel_models::{enums, user::dashboard_metadata as storage};use error_stack::{report, ResultExt};use router_env::instrument;-use storage_impl::MockDb;+use storage_impl::{DatabaseStore, MockDb};use crate::{- connection,core::errors::{self, CustomResult},services::Store,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait DashboardMetadataInterface {async fn insert_metadata(@@ -77,7 +77,7 @@ impl DashboardMetadataInterface for Store {&self,metadata: storage::DashboardMetadataNew,) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {- let conn = connection::pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;metadata.insert(&conn).await@@ -94,7 +94,7 @@ impl DashboardMetadataInterface for Store {data_key: enums::DashboardMetadata,dashboard_metadata_update: storage::DashboardMetadataUpdate,) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {- let conn = connection::pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;storage::DashboardMetadata::update(&conn,user_id,@@ -116,7 +116,7 @@ impl DashboardMetadataInterface for Store {org_id: &id_type::OrganizationId,data_keys: Vec<enums::DashboardMetadata>,) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {- let conn = connection::pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::DashboardMetadata::find_user_scoped_dashboard_metadata(&conn,user_id.to_owned(),@@ -135,7 +135,7 @@ impl DashboardMetadataInterface for Store {org_id: &id_type::OrganizationId,data_keys: Vec<enums::DashboardMetadata>,) -> CustomResult<Vec<storage::DashboardMetadata>, errors::StorageError> {- let conn = connection::pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::DashboardMetadata::find_merchant_scoped_dashboard_metadata(&conn,merchant_id.to_owned(),@@ -155,7 +155,7 @@ impl DashboardMetadataInterface for Store {profile_id: Option<String>,data_key: enums::DashboardMetadata,) -> CustomResult<Option<storage::DashboardMetadata>, errors::StorageError> {- let conn = connection::pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::DashboardMetadata::find_dashboard_metadata_by_user_merchant_org_profile_key(&conn,user_id.to_owned(),@@ -174,7 +174,7 @@ impl DashboardMetadataInterface for Store {user_id: &str,merchant_id: &id_type::MerchantId,) -> CustomResult<bool, errors::StorageError> {- let conn = connection::pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;storage::DashboardMetadata::delete_all_user_scoped_dashboard_metadata_by_merchant_id(&conn,user_id.to_owned(),@@ -191,7 +191,7 @@ impl DashboardMetadataInterface for Store {merchant_id: &id_type::MerchantId,data_key: enums::DashboardMetadata,) -> CustomResult<storage::DashboardMetadata, errors::StorageError> {- let conn = connection::pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;storage::DashboardMetadata::delete_user_scoped_dashboard_metadata_by_merchant_id_data_key(&conn,user_id.to_owned(),@@ -207,7 +207,7 @@ impl DashboardMetadataInterface for Store {&self,user_id: &str,) -> CustomResult<bool, errors::StorageError> {- let conn = connection::pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;storage::DashboardMetadata::delete_all_by_user_id(&conn, user_id.to_owned()).await.map_err(|error| report!(errors::StorageError::from(error)))diff --git a/crates/router/src/db/dispute.rs b/crates/router/src/db/dispute.rsindex 39165664f1..77eac03f2f 100644--- a/crates/router/src/db/dispute.rs+++ b/crates/router/src/db/dispute.rs@@ -8,6 +8,7 @@ use crate::{types::storage::{self, enums},};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait DisputeInterface {async fn insert_dispute(diff --git a/crates/router/src/db/dynamic_routing_stats.rs b/crates/router/src/db/dynamic_routing_stats.rsindex 59448e1ded..add5b8aa48 100644--- a/crates/router/src/db/dynamic_routing_stats.rs+++ b/crates/router/src/db/dynamic_routing_stats.rs@@ -10,6 +10,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait DynamicRoutingStatsInterface {async fn insert_dynamic_routing_stat_entry(@@ -108,9 +109,11 @@ impl DynamicRoutingStatsInterface for KafkaStore {&self,dynamic_routing_stat: storage::DynamicRoutingStatsNew,) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {- self.diesel_store- .insert_dynamic_routing_stat_entry(dynamic_routing_stat)- .await+ DynamicRoutingStatsInterface::insert_dynamic_routing_stat_entry(+ &self.diesel_store,+ dynamic_routing_stat,+ )+ .await}async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(@@ -118,9 +121,12 @@ impl DynamicRoutingStatsInterface for KafkaStore {attempt_id: String,merchant_id: &common_utils::id_type::MerchantId,) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {- self.diesel_store- .find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(attempt_id, merchant_id)- .await+ DynamicRoutingStatsInterface::find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(+ &self.diesel_store,+ attempt_id,+ merchant_id,+ )+ .await}async fn update_dynamic_routing_stats(@@ -129,8 +135,12 @@ impl DynamicRoutingStatsInterface for KafkaStore {merchant_id: &common_utils::id_type::MerchantId,data: storage::DynamicRoutingStatsUpdate,) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {- self.diesel_store- .update_dynamic_routing_stats(attempt_id, merchant_id, data)- .await+ DynamicRoutingStatsInterface::update_dynamic_routing_stats(+ &self.diesel_store,+ attempt_id,+ merchant_id,+ data,+ )+ .await}}diff --git a/crates/router/src/db/events.rs b/crates/router/src/db/events.rsindex 6c80631a35..a5b648e3d6 100644--- a/crates/router/src/db/events.rs+++ b/crates/router/src/db/events.rs@@ -18,6 +18,7 @@ use crate::{},};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait EventInterfacewhere@@ -1929,24 +1930,23 @@ mod tests {let aes_key = services::generate_aes256_key()?;- let merchant_key_store = state- .store- .insert_merchant_key_store(- domain::MerchantKeyStore {- merchant_id: merchant_id.clone(),- key: domain::types::crypto_operation(- key_manager_state,- type_name!(domain::MerchantKeyStore),- domain::types::CryptoOperation::EncryptLocally(aes_key.to_vec().into()),- Identifier::Merchant(merchant_id.to_owned()),- master_key,- )- .await?- .try_into_operation()?,- created_at: datetime!(2023-02-01 0:00),- },- &master_key.to_vec().into(),+ let merchant_key_store_to_insert = domain::MerchantKeyStore {+ merchant_id: merchant_id.clone(),+ key: domain::types::crypto_operation(+ key_manager_state,+ type_name!(domain::MerchantKeyStore),+ domain::types::CryptoOperation::EncryptLocally(aes_key.to_vec().into()),+ Identifier::Merchant(merchant_id.to_owned()),+ master_key,)+ .await?+ .try_into_operation()?,+ created_at: datetime!(2023-02-01 0:00),+ };+ let key_store_master_key = master_key.to_vec().into();+ let merchant_key_store = state+ .accounts_store+ .insert_merchant_key_store(merchant_key_store_to_insert, &key_store_master_key).await?;let merchant_account_to_insert = MerchantAccount::from(MerchantAccountSetter {@@ -2005,7 +2005,7 @@ mod tests {apple_pay_certificates_encrypted: None,});let merchant_account = state- .store+ .accounts_store.insert_merchant(merchant_account_to_insert, &merchant_key_store).await?;@@ -2099,8 +2099,8 @@ mod tests {});let business_profile = state- .store- .insert_business_profile(&merchant_key_store.clone(), business_profile_to_insert)+ .accounts_store+ .insert_business_profile(&merchant_key_store, business_profile_to_insert).await?;// Same inputs for all threadsdiff --git a/crates/router/src/db/file.rs b/crates/router/src/db/file.rsindex 5ce854ca04..f831e08783 100644--- a/crates/router/src/db/file.rs+++ b/crates/router/src/db/file.rs@@ -8,6 +8,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait FileMetadataInterface {async fn insert_file_metadata(diff --git a/crates/router/src/db/fraud_check.rs b/crates/router/src/db/fraud_check.rsindex 4abb38f3dc..6293710b58 100644--- a/crates/router/src/db/fraud_check.rs+++ b/crates/router/src/db/fraud_check.rs@@ -9,6 +9,7 @@ use crate::{services::Store,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait FraudCheckInterface {async fn insert_fraud_check_response(diff --git a/crates/router/src/db/generic_link.rs b/crates/router/src/db/generic_link.rsindex d389452e29..b980d43fac 100644--- a/crates/router/src/db/generic_link.rs+++ b/crates/router/src/db/generic_link.rs@@ -9,6 +9,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait GenericLinkInterface {async fn find_generic_link_by_link_id(diff --git a/crates/router/src/db/gsm.rs b/crates/router/src/db/gsm.rsindex c41877900e..81c6590951 100644--- a/crates/router/src/db/gsm.rs+++ b/crates/router/src/db/gsm.rs@@ -9,6 +9,7 @@ use crate::{services::Store,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait GsmInterface {async fn add_gsm_rule(diff --git a/crates/router/src/db/health_check.rs b/crates/router/src/db/health_check.rsindex b0795acdad..65a1c39824 100644--- a/crates/router/src/db/health_check.rs+++ b/crates/router/src/db/health_check.rs@@ -9,6 +9,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait HealthCheckDbInterface {async fn health_check_db(&self) -> CustomResult<(), errors::HealthCheckDBError>;diff --git a/crates/router/src/db/hierarchical_resource.rs b/crates/router/src/db/hierarchical_resource.rsindex b5ae12f8ab..c57697395b 100644--- a/crates/router/src/db/hierarchical_resource.rs+++ b/crates/router/src/db/hierarchical_resource.rs@@ -1 +1,3 @@-pub use hyperswitch_domain_models::hierarchical_resource::{self, HierarchicalResourceInterface};+pub use hyperswitch_domain_models::hierarchical_resource::{+ self, HierarchicalResourceInterface, TrackedHierarchicalResourceInterface,+};diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex 5410de6386..30f77fbac8 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -3847,7 +3847,7 @@ impl StorageInterface for KafkaStore {Box::new(self.clone())}fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState) {- self.diesel_store.set_key_manager_state(key_manager_state);+ StorageInterface::set_key_manager_state(&mut self.diesel_store, key_manager_state);}}@@ -3856,7 +3856,11 @@ impl GlobalStorageInterface for KafkaStore {Box::new(self.clone())}}-impl AccountsStorageInterface for KafkaStore {}+impl AccountsStorageInterface for KafkaStore {+ fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState) {+ StorageInterface::set_key_manager_state(self, key_manager_state);+ }+}impl PaymentMethodsStorageInterface for KafkaStore {}diff --git a/crates/router/src/db/locker_mock_up.rs b/crates/router/src/db/locker_mock_up.rsindex 24d4b84b5a..89d42db668 100644--- a/crates/router/src/db/locker_mock_up.rs+++ b/crates/router/src/db/locker_mock_up.rs@@ -8,6 +8,7 @@ use crate::{types::storage,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait LockerMockUpInterface {async fn find_locker_by_card_id(diff --git a/crates/router/src/db/mandate.rs b/crates/router/src/db/mandate.rsindex 003314a7f0..8069f234da 100644--- a/crates/router/src/db/mandate.rs+++ b/crates/router/src/db/mandate.rs@@ -6,6 +6,7 @@ use crate::{types::storage::{self as storage_types, enums::MerchantStorageScheme},};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait MandateInterface {async fn find_mandate_by_merchant_id_mandate_id(diff --git a/crates/router/src/db/merchant_account.rs b/crates/router/src/db/merchant_account.rsindex 0611d063d3..94f2b1c7f9 100644--- a/crates/router/src/db/merchant_account.rs+++ b/crates/router/src/db/merchant_account.rs@@ -1 +1,3 @@-pub use hyperswitch_domain_models::merchant_account::{self, MerchantAccountInterface};+pub use hyperswitch_domain_models::merchant_account::{+ self, MerchantAccountInterface, TrackedMerchantAccountInterface,+};diff --git a/crates/router/src/db/merchant_connector_account.rs b/crates/router/src/db/merchant_connector_account.rsindex a838e3a6ff..6af32ec3fe 100644--- a/crates/router/src/db/merchant_connector_account.rs+++ b/crates/router/src/db/merchant_connector_account.rs@@ -1,6 +1,8 @@use common_utils::ext_traits::{ByteSliceExt, Encode};use error_stack::ResultExt;-pub use hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccountInterface;+pub use hyperswitch_domain_models::merchant_connector_account::{+ MerchantConnectorAccountInterface, TrackedMerchantConnectorAccountInterface,+};use router_env::instrument;use storage_impl::redis::kv_store::RedisConnInterface;diff --git a/crates/router/src/db/merchant_key_store.rs b/crates/router/src/db/merchant_key_store.rsindex 659044e39d..06bd90ae46 100644--- a/crates/router/src/db/merchant_key_store.rs+++ b/crates/router/src/db/merchant_key_store.rs@@ -1,4 +1,6 @@-pub use hyperswitch_domain_models::merchant_key_store::{self, MerchantKeyStoreInterface};+pub use hyperswitch_domain_models::merchant_key_store::{+ self, MerchantKeyStoreInterface, TrackedMerchantKeyStoreInterface,+};#[cfg(test)]mod tests {diff --git a/crates/router/src/db/organization.rs b/crates/router/src/db/organization.rsindex 96f30cd12e..78951a2704 100644--- a/crates/router/src/db/organization.rs+++ b/crates/router/src/db/organization.rs@@ -4,9 +4,11 @@ use error_stack::report;use router_env::instrument;#[cfg(feature = "accounts_cache")]use storage_impl::redis::cache::{self, CacheKind};+use storage_impl::DatabaseStore;-use crate::{connection, core::errors, services::Store};+use crate::{core::errors, services::Store};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait OrganizationInterface {async fn insert_organization(@@ -33,7 +35,7 @@ impl OrganizationInterface for Store {&self,organization: storage::OrganizationNew,) -> CustomResult<storage::Organization, errors::StorageError> {- let conn = connection::pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;organization.insert(&conn).await@@ -46,7 +48,7 @@ impl OrganizationInterface for Store {org_id: &id_type::OrganizationId,) -> CustomResult<storage::Organization, errors::StorageError> {let find_call = || async {- let conn = connection::pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::Organization::find_by_org_id(&conn, org_id.to_owned()).await.map_err(|error| report!(errors::StorageError::from(error)))@@ -75,7 +77,7 @@ impl OrganizationInterface for Store {org_id: &id_type::OrganizationId,update: storage::OrganizationUpdate,) -> CustomResult<storage::Organization, errors::StorageError> {- let conn = connection::pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let update_call = || async {storage::Organization::update_by_org_id(&conn, org_id.to_owned(), update).awaitdiff --git a/crates/router/src/db/payment_link.rs b/crates/router/src/db/payment_link.rsindex 840c43e7d7..06e90eb7a7 100644--- a/crates/router/src/db/payment_link.rs+++ b/crates/router/src/db/payment_link.rs@@ -9,6 +9,7 @@ use crate::{types::storage::{self, PaymentLinkDbExt},};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait PaymentLinkInterface {async fn find_payment_link_by_payment_link_id(diff --git a/crates/router/src/db/payment_method_session.rs b/crates/router/src/db/payment_method_session.rsindex 1aebea49fd..96cfd80fbe 100644--- a/crates/router/src/db/payment_method_session.rs+++ b/crates/router/src/db/payment_method_session.rs@@ -3,6 +3,7 @@ use crate::core::errors::{self, CustomResult};use crate::db::MockDb;#[cfg(feature = "v2")]+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait PaymentMethodsSessionInterface {async fn insert_payment_methods_session(@@ -34,6 +35,7 @@ pub trait PaymentMethodsSessionInterface {}#[cfg(feature = "v1")]+#[router_derive::track_async_interface]pub trait PaymentMethodsSessionInterface {}#[cfg(feature = "v1")]diff --git a/crates/router/src/db/refund.rs b/crates/router/src/db/refund.rsindex 9e42aa9cf6..1edbfebe31 100644--- a/crates/router/src/db/refund.rs+++ b/crates/router/src/db/refund.rs@@ -15,6 +15,7 @@ use crate::{#[cfg(feature = "olap")]const MAX_LIMIT: usize = 100;+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait RefundInterface {#[cfg(feature = "v1")]diff --git a/crates/router/src/db/relay.rs b/crates/router/src/db/relay.rsindex 0a3d411088..cf9f3e9282 100644--- a/crates/router/src/db/relay.rs+++ b/crates/router/src/db/relay.rs@@ -11,6 +11,7 @@ use crate::{services::Store,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait RelayInterface {async fn insert_relay(@@ -178,9 +179,7 @@ impl RelayInterface for KafkaStore {merchant_key_store: &domain::MerchantKeyStore,new: hyperswitch_domain_models::relay::Relay,) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {- self.diesel_store- .insert_relay(merchant_key_store, new)- .await+ RelayInterface::insert_relay(&self.diesel_store, merchant_key_store, new).await}async fn update_relay(@@ -189,9 +188,13 @@ impl RelayInterface for KafkaStore {current_state: hyperswitch_domain_models::relay::Relay,relay_update: hyperswitch_domain_models::relay::RelayUpdate,) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {- self.diesel_store- .update_relay(merchant_key_store, current_state, relay_update)- .await+ RelayInterface::update_relay(+ &self.diesel_store,+ merchant_key_store,+ current_state,+ relay_update,+ )+ .await}async fn find_relay_by_id(@@ -199,9 +202,7 @@ impl RelayInterface for KafkaStore {merchant_key_store: &domain::MerchantKeyStore,relay_id: &common_utils::id_type::RelayId,) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {- self.diesel_store- .find_relay_by_id(merchant_key_store, relay_id)- .await+ RelayInterface::find_relay_by_id(&self.diesel_store, merchant_key_store, relay_id).await}async fn find_relay_by_profile_id_connector_reference_id(@@ -210,12 +211,12 @@ impl RelayInterface for KafkaStore {profile_id: &common_utils::id_type::ProfileId,connector_reference_id: &str,) -> CustomResult<hyperswitch_domain_models::relay::Relay, errors::StorageError> {- self.diesel_store- .find_relay_by_profile_id_connector_reference_id(- merchant_key_store,- profile_id,- connector_reference_id,- )- .await+ RelayInterface::find_relay_by_profile_id_connector_reference_id(+ &self.diesel_store,+ merchant_key_store,+ profile_id,+ connector_reference_id,+ )+ .await}}diff --git a/crates/router/src/db/reverse_lookup.rs b/crates/router/src/db/reverse_lookup.rsindex 1f27487685..3303065de5 100644--- a/crates/router/src/db/reverse_lookup.rs+++ b/crates/router/src/db/reverse_lookup.rs@@ -7,6 +7,7 @@ use crate::{},};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait ReverseLookupInterface {async fn insert_reverse_lookup(diff --git a/crates/router/src/db/routing_algorithm.rs b/crates/router/src/db/routing_algorithm.rsindex 9cb87da0b8..8bd9fea830 100644--- a/crates/router/src/db/routing_algorithm.rs+++ b/crates/router/src/db/routing_algorithm.rs@@ -13,6 +13,7 @@ use crate::{type StorageResult<T> = CustomResult<T, errors::StorageError>;+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait RoutingAlgorithmInterface {async fn insert_routing_algorithm(diff --git a/crates/router/src/db/unified_translations.rs b/crates/router/src/db/unified_translations.rsindex 2eebae08db..5fc4f699a6 100644--- a/crates/router/src/db/unified_translations.rs+++ b/crates/router/src/db/unified_translations.rs@@ -8,6 +8,7 @@ use crate::{services::Store,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait UnifiedTranslationsInterface {async fn add_unfied_translation(diff --git a/crates/router/src/db/user/sample_data.rs b/crates/router/src/db/user/sample_data.rsindex 568d9d9b4d..6aff540c8d 100644--- a/crates/router/src/db/user/sample_data.rs+++ b/crates/router/src/db/user/sample_data.rs@@ -18,6 +18,7 @@ use storage_impl::errors::StorageError;use crate::{connection::pg_connection_write, core::errors::CustomResult, services::Store};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait BatchSampleDataInterface {#[cfg(feature = "v1")]diff --git a/crates/router/src/db/user/theme.rs b/crates/router/src/db/user/theme.rsindex 853cd97dd6..351add5c88 100644--- a/crates/router/src/db/user/theme.rs+++ b/crates/router/src/db/user/theme.rs@@ -9,6 +9,7 @@ use crate::{services::Store,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait ThemeInterface {async fn insert_theme(diff --git a/crates/router/src/db/user_authentication_method.rs b/crates/router/src/db/user_authentication_method.rsindex 40c090763f..cc372a7d60 100644--- a/crates/router/src/db/user_authentication_method.rs+++ b/crates/router/src/db/user_authentication_method.rs@@ -9,6 +9,7 @@ use crate::{services::Store,};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait UserAuthenticationMethodInterface {async fn insert_user_authentication_method(diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex c882fd2248..db5e31ca94 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1,4 +1,4 @@-use std::{collections::HashMap, future::Future, panic::Location, sync::Arc};+use std::{collections::HashMap, sync::Arc};use actix_web::{web, Scope};#[cfg(all(feature = "olap", feature = "v1"))]@@ -134,7 +134,7 @@ pub struct SessionState {pub store: Box<dyn StorageInterface>,/// Global store is used for global schema operations in tables like Users and Tenantspub global_store: Box<dyn GlobalStorageInterface>,- accounts_store: Box<dyn AccountsStorageInterface>,+ pub accounts_store: Box<dyn AccountsStorageInterface>,pub conf: Arc<settings::Settings<RawSecret>>,pub api_client: Box<dyn crate::services::ApiClient>,pub event_handler: EventsHandler,@@ -176,29 +176,15 @@ impl scheduler::SchedulerSessionState for SessionState {self.api_client.add_request_id(request_id.clone());self.store.add_request_id(request_id.to_string());self.global_store.add_request_id(request_id.to_string());- #[cfg(feature = "deja")]- {- self.accounts_store.add_request_id(request_id.to_string());- }+ self.accounts_store.add_request_id(request_id.to_string());self.request_id.replace(request_id);}}impl SessionState {- /// Run an accounts operation with this call site's location in scope.- /// Use one call per query to retain each query's location.- #[track_caller]- pub fn track_accounts_query<'s, F, Fut>(- &'s self,- operation: F,- ) -> impl Future<Output = Fut::Output> + 's- where- F: FnOnce(&'s dyn AccountsStorageInterface) -> Fut + 's,- Fut: Future + 's,- {- let origin = Location::caller();- router_env::call_origin::with_origin(origin, async move {- operation(self.accounts_store.as_ref()).await- })+ /// Keep key-manager context in sync across the main and accounts stores.+ pub fn set_key_manager_state(&mut self, key_manager_state: KeyManagerState) {+ self.store.set_key_manager_state(key_manager_state.clone());+ self.accounts_store.set_key_manager_state(key_manager_state);}pub(crate) fn get_webhook_registration_base_url(@@ -328,10 +314,7 @@ impl SessionStateInfo for SessionState {self.api_client.add_request_id(request_id.clone());self.store.add_request_id(request_id.to_string());self.global_store.add_request_id(request_id.to_string());- #[cfg(feature = "deja")]- {- self.accounts_store.add_request_id(request_id.to_string());- }+ self.accounts_store.add_request_id(request_id.to_string());self.request_id.replace(request_id);}@@ -770,11 +753,9 @@ impl AppState {let tenant_conf = self.conf.multitenancy.get_tenant(tenant).ok_or_else(err)?;let mut event_handler = self.event_handler.clone();event_handler.add_tenant(tenant_conf);- let mut store = self.stores.get(tenant).ok_or_else(err)?.clone();let key_manager_state = KeyManagerState::foreign_from((self.as_ref(), tenant_conf.clone()));- store.set_key_manager_state(key_manager_state);- Ok(SessionState {- store,+ let mut state = SessionState {+ store: self.stores.get(tenant).ok_or_else(err)?.clone(),global_store: self.global_store.clone(),accounts_store: self.accounts_store.get(tenant).ok_or_else(err)?.clone(),conf: Arc::clone(&self.conf),@@ -799,7 +780,9 @@ impl AppState {superposition_service: self.superposition_service.clone(),payment_metrics_context: None,payment_callback_config: Arc::default(),- })+ };+ state.set_key_manager_state(key_manager_state);+ Ok(state)}pub fn process_env_mappings(diff --git a/crates/router/src/routes/hierarchical_resources.rs b/crates/router/src/routes/hierarchical_resources.rsindex 9eb7134668..65f8a294ed 100644--- a/crates/router/src/routes/hierarchical_resources.rs+++ b/crates/router/src/routes/hierarchical_resources.rs@@ -32,7 +32,7 @@ async fn resolve_profile_from_header() -> Result<crate::types::domain::Profile, error_stack::Report<errors::ApiErrorResponse>> {let processor = auth_data.platform.get_processor();state- .store+ .accounts_store.find_business_profile_by_merchant_id_profile_id(processor.get_key_store(),processor.get_account().get_id(),diff --git a/crates/router/src/routes/payment_methods.rs b/crates/router/src/routes/payment_methods.rsindex 368dd0ddb0..2cc04ad5af 100644--- a/crates/router/src/routes/payment_methods.rs+++ b/crates/router/src/routes/payment_methods.rs@@ -471,17 +471,15 @@ async fn get_merchant_account(state: &SessionState,merchant_id: &id_type::MerchantId,) -> CustomResult<(MerchantKeyStore, domain::MerchantAccount), errors::ApiErrorResponse> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;@@ -539,13 +537,11 @@ pub async fn migrate_payment_methods(if let Some(connector_customer_details) = &record.connector_customer_details {for connector_customer in connector_customer_details {if !mca_cache.contains_key(&connector_customer.merchant_connector_id) {- let mca = state- .store- .find_by_merchant_connector_account_merchant_id_merchant_connector_id(- &merchant_id,- &connector_customer.merchant_connector_id,- platform.get_processor().get_key_store(),- )+ let mca = state.accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ &merchant_id,+ &connector_customer.merchant_connector_id,+ platform.get_processor().get_key_store(),+ ).await.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {diff --git a/crates/router/src/routes/payment_methods/migrate.rs b/crates/router/src/routes/payment_methods/migrate.rsindex e6454e1531..a2d5724a14 100644--- a/crates/router/src/routes/payment_methods/migrate.rs+++ b/crates/router/src/routes/payment_methods/migrate.rs@@ -943,12 +943,10 @@ async fn get_merchant_contexts_for_batch(state: &SessionState,merchant_ids: Vec<id_type::MerchantId>,) -> MerchantContextBatch {+ let key_store_master_key = state.store.get_master_key().to_vec().into();match state- .store- .list_multiple_key_stores(- merchant_ids.clone(),- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .list_multiple_key_stores(merchant_ids.clone(), &key_store_master_key).await{Err(error) => {@@ -959,7 +957,7 @@ async fn get_merchant_contexts_for_batch()}Ok(key_stores) => match state- .store+ .accounts_store.list_multiple_merchant_accounts(merchant_ids.clone()).await{diff --git a/crates/router/src/routes/payments.rs b/crates/router/src/routes/payments.rsindex d4ff299bbe..43651c1b2e 100644--- a/crates/router/src/routes/payments.rs+++ b/crates/router/src/routes/payments.rs@@ -2918,9 +2918,7 @@ async fn set_payment_confirm_metrics_context());state.payment_metrics_context = Some(context);- state- .store- .set_key_manager_state(KeyManagerState::from(&*state));+ state.set_key_manager_state(KeyManagerState::from(&*state));context}diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rsindex 6ef12f58b1..114663d1b1 100644--- a/crates/router/src/services/api.rs+++ b/crates/router/src/services/api.rs@@ -397,14 +397,16 @@ wherestate.event_handler().log_event(&api_event);- if let Some(read_ledger) = session_state.get_read_ledger() {- let duplicate_reads = read_ledger.duplicate_reads();- if !duplicate_reads.is_empty() {- logger::debug!(- flow = %read_ledger.flow(),- ?duplicate_reads,- "Duplicate database reads in session"- );+ if tracing::enabled!(tracing::Level::DEBUG) {+ if let Some(read_ledger) = session_state.get_read_ledger() {+ let duplicate_reads = read_ledger.duplicate_reads();+ if !duplicate_reads.is_empty() {+ logger::debug!(+ flow = %read_ledger.flow(),+ ?duplicate_reads,+ "Duplicate database reads in session"+ );+ }}}diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex c5597ffc7f..32a7a39285 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -646,24 +646,25 @@ where.attach_printable("API key has expired");}- let key_store = state- .store()+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store.get_merchant_key_store_by_merchant_id(&stored_api_key.merchant_id,- &state.store().get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(errors::ApiErrorResponse::Unauthorized).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let initiator_merchant = state- .store()+ let initiator_merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_profile_id(&key_store, &profile_id).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -751,11 +752,12 @@ where.attach_printable("API key has expired");}- let key_store = state- .store()+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store.get_merchant_key_store_by_merchant_id(&stored_api_key.merchant_id,- &state.store().get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(errors::ApiErrorResponse::Unauthorized)@@ -770,8 +772,8 @@ where}).change_context(errors::ApiErrorResponse::Unauthorized)?;- let initiator_merchant = state- .store()+ let initiator_merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -802,8 +804,8 @@ wherelet profile = match profile_id {Some(profile_id) => {- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&profile_id,@@ -997,18 +999,19 @@ where.attach_printable("API key has expired");}- let key_store = state- .store()+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store.get_merchant_key_store_by_merchant_id(&stored_api_key.merchant_id,- &state.store().get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(errors::ApiErrorResponse::Unauthorized).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant_account = state- .store()+ let merchant_account = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)@@ -1082,18 +1085,19 @@ where.attach_printable("API key has expired");}- let key_store = state- .store()+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store.get_merchant_key_store_by_merchant_id(&stored_api_key.merchant_id,- &state.store().get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(errors::ApiErrorResponse::Unauthorized).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let initiator_merchant_account = state- .store()+ let initiator_merchant_account = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)@@ -1156,17 +1160,15 @@ impl PlatformOrgAdminAuthWithMerchantIdFromRoute {merchant_id: &id_type::MerchantId,state: &A,) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> {- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -1437,8 +1439,8 @@ wherelet profile_id = HeaderMapStruct::new(request_headers).get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_profile_id(auth_data.platform.get_processor().get_key_store(),&profile_id,@@ -1467,18 +1469,16 @@ async fn construct_authentication_data<A>(whereA: SessionStateInfo + Sync,{- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::Unauthorized).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let initiator_merchant = state- .store()+ let initiator_merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -1509,8 +1509,8 @@ wherelet profile = match profile_id {Some(profile_id) => {- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&profile_id,@@ -1786,17 +1786,15 @@ wherelet merchant_id = self.0.clone();- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -1847,21 +1845,19 @@ wherelet profile_id =get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?.get_required_value(headers::X_PROFILE_ID)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store, &merchant_id, &profile_id).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -1910,17 +1906,15 @@ wherelet merchant_id = self.0.clone();- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -1994,18 +1988,19 @@ where.attach_printable("API key has expired");}- let key_store = state- .store()+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store.get_merchant_key_store_by_merchant_id(&stored_api_key.merchant_id,- &state.store().get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(errors::ApiErrorResponse::Unauthorized).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -2051,17 +2046,15 @@ impl AdminApiAuthWithApiKeyFallbackAndMerchantIdFromRoute {merchant_id: &id_type::MerchantId,state: &A,) -> RouterResult<(domain::MerchantKeyStore, domain::MerchantAccount)> {- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -2317,17 +2310,15 @@ wherelet merchant_id = HeaderMapStruct::new(request_headers).get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -2379,21 +2370,19 @@ whereget_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?.get_required_value(headers::X_PROFILE_ID)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store, &merchant_id, &profile_id).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -2443,17 +2432,15 @@ wherelet merchant_id = HeaderMapStruct::new(request_headers).get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -2488,17 +2475,15 @@ wherethrow_error_if_platform_merchant_authentication_required(request_headers)?;}- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &self.0,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&self.0, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&self.0, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -2591,22 +2576,20 @@ wherelet profile_id =get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?.get_required_value(headers::X_PROFILE_ID)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store, &merchant_id, &profile_id).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -2685,17 +2668,15 @@ impl<F> InternalMerchantIdProfileIdAuth<F> {.attach_printable("Internal API key authentication failed");}- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&merchant_id,@@ -2704,8 +2685,8 @@ impl<F> InternalMerchantIdProfileIdAuth<F> {.await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let initiator_merchant = state- .store()+ let initiator_merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -2860,17 +2841,15 @@ wherethrow_error_if_platform_merchant_authentication_required(request_headers)?;}- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &self.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&self.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&self.merchant_id,@@ -2878,8 +2857,8 @@ where).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&self.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -2930,8 +2909,8 @@ where_request_headers: &HeaderMap,state: &A,) -> RouterResult<(AuthenticationData, AuthenticationType)> {- let (merchant_account, key_store) = state- .store()+ let (merchant_account, key_store) = (state.session_state())+ .accounts_store.find_merchant_account_by_publishable_key(self.publishable_key.as_str()).await.map_err(|e| {@@ -2942,8 +2921,8 @@ where}})?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_profile_id(&key_store, &self.profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -3039,18 +3018,19 @@ where.attach_printable("API key has expired");}- let key_store = state- .store()+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store.get_merchant_key_store_by_merchant_id(&stored_api_key.merchant_id,- &state.store().get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(errors::ApiErrorResponse::Unauthorized).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let initiator_merchant = state- .store()+ let initiator_merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&stored_api_key.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -3079,8 +3059,8 @@ where).await?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(platform.get_processor().get_key_store(),platform.get_processor().get_account().get_id(),@@ -3185,8 +3165,8 @@ where}}- let (initiator_merchant, key_store) = state- .store()+ let (initiator_merchant, key_store) = (state.session_state())+ .accounts_store.find_merchant_account_by_publishable_key(publishable_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -3211,8 +3191,8 @@ wherereturn Err(errors::ApiErrorResponse::Unauthorized.into());}- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,platform.get_processor().get_account().get_id(),@@ -3348,8 +3328,8 @@ whereget_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;// Find initiator merchant and key store- let (initiator_merchant, key_store) = state- .store()+ let (initiator_merchant, key_store) = (state.session_state())+ .accounts_store.find_merchant_account_by_publishable_key(publishable_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -3411,8 +3391,8 @@ where.get_required_value(headers::X_PROFILE_ID)?;// Find initiator merchant and key store- let (initiator_merchant, key_store) = state- .store()+ let (initiator_merchant, key_store) = (state.session_state())+ .accounts_store.find_merchant_account_by_publishable_key(publishable_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;@@ -3442,8 +3422,8 @@ where.await?;// Find and validate profile after merchant resolution- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(platform.get_processor().get_key_store(),platform.get_processor().get_account().get_id(),@@ -3510,8 +3490,8 @@ where.platform_publishable_key{Some(ref platform_pub_key) => {- let (platform_merchant, platform_key_store) = state- .store()+ let (platform_merchant, platform_key_store) = (state.session_state())+ .accounts_store.find_merchant_account_by_publishable_key(platform_pub_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)@@ -3520,8 +3500,8 @@ where(platform_merchant, platform_key_store)}None => {- let (processor_merchant, processor_key_store) = state- .store()+ let (processor_merchant, processor_key_store) = (state.session_state())+ .accounts_store.find_merchant_account_by_publishable_key(&sdk_auth.publishable_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)@@ -3617,8 +3597,8 @@ wherelogger::info!("Client session validation is disabled");}- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(platform.get_processor().get_key_store(),platform.get_processor().get_account().get_id(),@@ -3662,8 +3642,8 @@ where})?;// Look up processor by publishable key from SDK authorization- let (processor_merchant, processor_key_store) = state- .store()+ let (processor_merchant, processor_key_store) = (state.session_state())+ .accounts_store.find_merchant_account_by_publishable_key(&sdk_auth.publishable_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)@@ -3856,8 +3836,8 @@ where.platform_publishable_key{Some(ref platform_pub_key) => {- let (platform_merchant, platform_key_store) = state- .store()+ let (platform_merchant, platform_key_store) = (state.session_state())+ .accounts_store.find_merchant_account_by_publishable_key(platform_pub_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)@@ -3866,8 +3846,8 @@ where(platform_merchant, platform_key_store)}None => {- let (processor_merchant, processor_key_store) = state- .store()+ let (processor_merchant, processor_key_store) = (state.session_state())+ .accounts_store.find_merchant_account_by_publishable_key(&sdk_auth.publishable_key).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)@@ -3924,8 +3904,8 @@ where}}- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(platform.get_processor().get_key_store(),platform.get_processor().get_account().get_id(),@@ -4011,18 +3991,16 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.change_context(errors::ApiErrorResponse::InvalidJwtToken)?;@@ -4204,25 +4182,23 @@ wherereturn Err(report!(errors::ApiErrorResponse::InvalidJwtToken));}- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant account for the merchant id")?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -4341,18 +4317,16 @@ wherereturn Err(report!(errors::ApiErrorResponse::InvalidJwtToken));}- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -4360,8 +4334,8 @@ where).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)@@ -4430,18 +4404,16 @@ wherereturn Err(report!(errors::ApiErrorResponse::InvalidJwtToken));}- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)@@ -4525,25 +4497,23 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.required_permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant account for the merchant id")?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -4613,17 +4583,15 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.required_permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -4631,8 +4599,8 @@ where).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)@@ -4697,18 +4665,16 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.required_permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)@@ -4767,25 +4733,23 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.required_permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant account for the merchant id")?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -4860,18 +4824,16 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.required_permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)@@ -4887,8 +4849,8 @@ where.attach_printable("Profile id in JWT does not match profile id in route")})?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -4964,18 +4926,16 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.required_permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -4983,8 +4943,8 @@ where).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)@@ -5077,18 +5037,16 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)@@ -5099,8 +5057,8 @@ where.attach_printable("JWT merchant does not belong to JWT organization")})?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -5170,18 +5128,16 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -5190,8 +5146,8 @@ where.await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)@@ -5285,24 +5241,22 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.change_context(errors::ApiErrorResponse::InvalidJwtToken)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -5368,24 +5322,22 @@ wherelet role_info = authorization::get_role_info(state, &payload).await?;authorization::check_permission(self.permission, &role_info)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.change_context(errors::ApiErrorResponse::InvalidJwtToken)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -5531,24 +5483,22 @@ where&state.session_state().tenant.tenant_id,)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &payload.merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&payload.merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::Unauthorized).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&payload.merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&payload.merchant_id,@@ -5627,25 +5577,23 @@ where&state.session_state().tenant.tenant_id,)?;- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- payload.get_merchant_id(),- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(payload.get_merchant_id(), &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(payload.get_merchant_id(), &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant account for the merchant id")?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,payload.get_merchant_id(),@@ -5747,18 +5695,16 @@ where}};- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- payload.get_merchant_id(),- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(payload.get_merchant_id(), &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let profile = state- .store()+ let profile = (state.session_state())+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,payload.get_merchant_id(),@@ -5767,8 +5713,8 @@ where.await.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;- let merchant = state- .store()+ let merchant = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(payload.get_merchant_id(), &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)@@ -6674,18 +6620,16 @@ async fn get_connected_account_and_key_store<A>(whereA: SessionStateInfo + Sync,{- let key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &connected_merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&connected_merchant_id, &key_store_master_key).await.to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation).attach_printable("Failed to fetch merchant key store for the merchant id")?;- let connected_merchant_account = state- .store()+ let connected_merchant_account = (state.session_state())+ .accounts_store.find_merchant_account_by_merchant_id(&connected_merchant_id, &key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation)@@ -6832,7 +6776,8 @@ where{let session_state = state.session_state();let organization = session_state- .track_accounts_query(|db| db.find_organization_by_org_id(merchant_account.get_org_id()))+ .accounts_store+ .find_organization_by_org_id(merchant_account.get_org_id()).await.change_context(errors::ApiErrorResponse::InvalidPlatformOperation).attach_printable("Failed to fetch organization for connected merchant")?;@@ -6842,18 +6787,16 @@ where.attach_printable("Connected merchant missing platform merchant id")})?;- let platform_key_store = state- .store()- .get_merchant_key_store_by_merchant_id(- &platform_merchant_id,- &state.store().get_master_key().to_vec().into(),- )+ let key_store_master_key = state.store().get_master_key().to_vec().into();+ let platform_key_store = (state.session_state())+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&platform_merchant_id, &key_store_master_key).await.change_context(errors::ApiErrorResponse::InvalidPlatformOperation).attach_printable("Failed to fetch key store for platform merchant")?;- let platform_account = state- .store()+ let platform_account = session_state+ .accounts_store.find_merchant_account_by_merchant_id(&platform_merchant_id, &platform_key_store).await.to_not_found_response(errors::ApiErrorResponse::InvalidPlatformOperation)?;diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rsindex 42a9079168..eff5fafbe8 100644--- a/crates/router/src/types/domain/user.rs+++ b/crates/router/src/types/domain/user.rs@@ -250,7 +250,8 @@ pub struct NewUserOrganization(diesel_org::OrganizationNew);impl NewUserOrganization {pub async fn insert_org_in_db(self, state: SessionState) -> UserResult<Organization> {state- .track_accounts_query(|db| db.insert_organization(self.0))+ .accounts_store+ .insert_organization(self.0).await.map_err(|e| {if e.current_context().is_db_unique_violation() {@@ -448,12 +449,11 @@ impl NewUserMerchant {}pub async fn check_if_already_exists_in_db(&self, state: SessionState) -> UserResult<()> {+ let merchant_id = self.get_merchant_id();+ let key_store_master_key = state.store.get_master_key().to_vec().into();if state- .store- .get_merchant_key_store_by_merchant_id(- &self.get_merchant_id(),- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.is_ok(){@@ -544,18 +544,19 @@ impl NewUserMerchant {return Err(UserErrors::InternalServerError.into());};+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&merchant_account_response.merchant_id,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_account_response.merchant_id,&merchant_key_store,@@ -592,18 +593,19 @@ impl NewUserMerchant {..Default::default()};+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&merchant_account_response.id,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to retrieve merchant key store by merchant_id")?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_account_response.id,&merchant_key_store,@@ -930,9 +932,8 @@ impl NewUser {let organization_id = self.new_merchant.new_organization.get_organization_id();state- .track_accounts_query(|db| {- db.update_organization_by_org_id(&organization_id, org_update)- })+ .accounts_store+ .update_organization_by_org_id(&organization_id, org_update).await.change_context(UserErrors::InternalServerError).attach_printable("Failed to update organization with platform_merchant_id")?;diff --git a/crates/router/src/types/storage/payment_attempt.rs b/crates/router/src/types/storage/payment_attempt.rsindex 14c413ebb3..059ab0e9d7 100644--- a/crates/router/src/types/storage/payment_attempt.rs+++ b/crates/router/src/types/storage/payment_attempt.rs@@ -132,6 +132,8 @@ impl AttemptStatusExt for enums::AttemptStatus {feature = "dummy_connector"))]mod tests {+ use std::sync::Arc;+use hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt;use tokio::sync::oneshot;@@ -142,7 +144,7 @@ mod tests {types::{self, domain},};- async fn create_single_connection_test_transaction_pool() -> routes::AppState {+ async fn create_single_connection_test_session() -> routes::SessionState {// Set pool size to 1 and minimum idle connection size to 0std::env::set_var("ROUTER__MASTER_DATABASE__POOL_SIZE", "1");std::env::set_var("ROUTER__MASTER_DATABASE__MIN_IDLE", "0");@@ -152,19 +154,31 @@ mod tests {let conf = Settings::new().expect("invalid settings");let tx: oneshot::Sender<()> = oneshot::channel().0;let api_client = Box::new(services::MockApiClient);- Box::pin(routes::AppState::with_storage(- conf,- StorageImpl::PostgresqlTest,- tx,- api_client,- env!("CARGO_PKG_NAME"),- ))- .await+ let app_state = Arc::new(+ Box::pin(routes::AppState::with_storage(+ conf,+ StorageImpl::PostgresqlTest,+ tx,+ api_client,+ env!("CARGO_PKG_NAME"),+ ))+ .await,+ );+ let tenant_id = app_state+ .conf+ .multitenancy+ .get_tenant_ids()+ .first()+ .unwrap()+ .clone();+ app_state+ .get_session_state(&tenant_id, None, || ())+ .unwrap()}#[tokio::test]async fn test_payment_attempt_insert() {- let state = create_single_connection_test_transaction_pool().await;+ let state = create_single_connection_test_session().await;let payment_id =common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();let current_time = common_utils::date_time::now();@@ -263,15 +277,11 @@ mod tests {active_frm_id: Default::default(),};- let store = state- .stores- .get(state.conf.multitenancy.get_tenant_ids().first().unwrap())- .unwrap();- let key_store = store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &store.get_master_key().to_vec().into(),- )+ let store = state.store.as_ref();+ let key_store_master_key = store.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.unwrap();let processor_key_store = domain::ProcessorKeyStore::from_untagged(key_store);@@ -292,7 +302,7 @@ mod tests {/// Example of unit test/// Kind of test: state-based testingasync fn test_find_payment_attempt() {- let state = create_single_connection_test_transaction_pool().await;+ let state = create_single_connection_test_session().await;let current_time = common_utils::date_time::now();let payment_id =common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();@@ -392,15 +402,11 @@ mod tests {payment_account_reference: Default::default(),active_frm_id: Default::default(),};- let store = state- .stores- .get(state.conf.multitenancy.get_tenant_ids().first().unwrap())- .unwrap();- let key_store = store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &store.get_master_key().to_vec().into(),- )+ let store = state.store.as_ref();+ let key_store_master_key = store.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.unwrap();let processor_key_store = domain::ProcessorKeyStore::from_untagged(key_store);@@ -433,7 +439,7 @@ mod tests {/// Example of unit test/// Kind of test: state-based testingasync fn test_payment_attempt_mandate_field() {- let state = create_single_connection_test_transaction_pool().await;+ let state = create_single_connection_test_session().await;let uuid = common_utils::generate_uuid_v4().to_string();let merchant_id =common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant1"))@@ -536,15 +542,11 @@ mod tests {payment_account_reference: Default::default(),active_frm_id: Default::default(),};- let store = state- .stores- .get(state.conf.multitenancy.get_tenant_ids().first().unwrap())- .unwrap();- let key_store = store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &store.get_master_key().to_vec().into(),- )+ let store = state.store.as_ref();+ let key_store_master_key = store.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.unwrap();let processor_key_store = domain::ProcessorKeyStore::from_untagged(key_store);diff --git a/crates/router/src/utils.rs b/crates/router/src/utils.rsindex 17ae51a467..071b7132a6 100644--- a/crates/router/src/utils.rs+++ b/crates/router/src/utils.rs@@ -57,7 +57,6 @@ use crate::{errors::{self, CustomResult, RouterResult, StorageErrorExt},payments as payments_core, webhooks as webhooks_core,},- db::StorageInterface,headers::ACCEPT_LANGUAGE,logger,routes::{metrics, SessionState},@@ -358,17 +357,17 @@ pub async fn find_mca_from_authentication_id_type(.merchant_connector_id.ok_or(errors::ApiErrorResponse::InternalServerError).attach_printable("merchant_connector_id not present in authentication record")?;- db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(- platform.get_processor().get_account().get_id(),- &mca_id,- platform.get_processor().get_key_store(),- )- .await- .to_not_found_response(- errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ state+ .accounts_store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ platform.get_processor().get_account().get_id(),+ &mca_id,+ platform.get_processor().get_key_store(),+ )+ .await+ .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {id: mca_id.get_string_repr().to_string(),- },- )+ })}#[cfg(feature = "v2")]//get mca using id@@ -416,17 +415,19 @@ pub async fn get_mca_from_payment_intent(Some(merchant_connector_id) => {#[cfg(feature = "v1")]{- db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(- platform.get_processor().get_account().get_id(),- &merchant_connector_id,- platform.get_processor().get_key_store(),- )- .await- .to_not_found_response(- errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: merchant_connector_id.get_string_repr().to_string(),- },- )+ state+ .accounts_store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ platform.get_processor().get_account().get_id(),+ &merchant_connector_id,+ platform.get_processor().get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: merchant_connector_id.get_string_repr().to_string(),+ },+ )}#[cfg(feature = "v2")]{@@ -449,20 +450,22 @@ pub async fn get_mca_from_payment_intent(#[cfg(feature = "v1")]{- db.find_merchant_connector_account_by_profile_id_connector_name(- &profile_id,- connector_name,- platform.get_processor().get_key_store(),- )- .await- .to_not_found_response(- errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: format!(- "profile_id {} and connector_name {connector_name}",- profile_id.get_string_repr()- ),- },- )+ state+ .accounts_store+ .find_merchant_connector_account_by_profile_id_connector_name(+ &profile_id,+ connector_name,+ platform.get_processor().get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: format!(+ "profile_id {} and connector_name {connector_name}",+ profile_id.get_string_repr()+ ),+ },+ )}#[cfg(feature = "v2")]{@@ -503,17 +506,19 @@ pub async fn get_mca_from_payout_attempt(Some(merchant_connector_id) => {#[cfg(feature = "v1")]{- db.find_by_merchant_connector_account_merchant_id_merchant_connector_id(- platform.get_processor().get_account().get_id(),- &merchant_connector_id,- platform.get_processor().get_key_store(),- )- .await- .to_not_found_response(- errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: merchant_connector_id.get_string_repr().to_string(),- },- )+ state+ .accounts_store+ .find_by_merchant_connector_account_merchant_id_merchant_connector_id(+ platform.get_processor().get_account().get_id(),+ &merchant_connector_id,+ platform.get_processor().get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: merchant_connector_id.get_string_repr().to_string(),+ },+ )}#[cfg(feature = "v2")]{@@ -527,21 +532,23 @@ pub async fn get_mca_from_payout_attempt(None => {#[cfg(feature = "v1")]{- db.find_merchant_connector_account_by_profile_id_connector_name(- &payout.profile_id,- connector_name,- platform.get_processor().get_key_store(),- )- .await- .to_not_found_response(- errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: format!(- "profile_id {} and connector_name {}",- payout.profile_id.get_string_repr(),- connector_name- ),- },- )+ state+ .accounts_store+ .find_merchant_connector_account_by_profile_id_connector_name(+ &payout.profile_id,+ connector_name,+ platform.get_processor().get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: format!(+ "profile_id {} and connector_name {}",+ payout.profile_id.get_string_repr(),+ connector_name+ ),+ },+ )}#[cfg(feature = "v2")]{@@ -558,8 +565,6 @@ pub async fn get_mca_from_object_reference_id(platform: &domain::Platform,connector_name: &str,) -> CustomResult<domain::MerchantConnectorAccount, errors::ApiErrorResponse> {- let db = &*state.store;-#[cfg(feature = "v1")]let default_profile_id = platform.get_processor()@@ -574,24 +579,25 @@ pub async fn get_mca_from_object_reference_id(Some(profile_id) => {#[cfg(feature = "v1")]{- db.find_merchant_connector_account_by_profile_id_connector_name(- profile_id,- connector_name,- platform.get_processor().get_key_store(),- )- .await- .to_not_found_response(- errors::ApiErrorResponse::MerchantConnectorAccountNotFound {- id: format!(- "profile_id {} and connector_name {connector_name}",- profile_id.get_string_repr()- ),- },- )+ state+ .accounts_store+ .find_merchant_connector_account_by_profile_id_connector_name(+ profile_id,+ connector_name,+ platform.get_processor().get_key_store(),+ )+ .await+ .to_not_found_response(+ errors::ApiErrorResponse::MerchantConnectorAccountNotFound {+ id: format!(+ "profile_id {} and connector_name {connector_name}",+ profile_id.get_string_repr()+ ),+ },+ )}#[cfg(feature = "v2")]{- let _db = db;let _profile_id = profile_id;todo!()}@@ -1369,7 +1375,7 @@ pub async fn trigger_refund_outgoing_webhook(let refund_status = refund.refund_status;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), &profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -1469,7 +1475,7 @@ pub async fn trigger_payouts_webhook() -> RouterResult<()> {let profile_id = &payout_response.profile_id;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(), profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {@@ -1597,7 +1603,7 @@ pub async fn trigger_subscriptions_outgoing_webhook(}pub async fn get_payment_response_hash_key(- store: &dyn StorageInterface,+ state: &SessionState,key_store: &domain::MerchantKeyStore,auth: &AuthInfo,) -> Result<Option<String>, error_stack::Report<AnalyticsError>> {@@ -1608,7 +1614,8 @@ pub async fn get_payment_response_hash_key(..} => {let profile_id = profile_ids.first().ok_or(AnalyticsError::UnknownError)?;- let profile = store+ let profile = state+ .accounts_store.find_business_profile_by_merchant_id_profile_id(key_store, merchant_id, profile_id).await.change_context(AnalyticsError::UnknownError)?;@@ -1618,7 +1625,8 @@ pub async fn get_payment_response_hash_key(#[cfg(feature = "v1")]{let merchant_id = merchant_ids.first().ok_or(AnalyticsError::UnknownError)?;- let merchant = store+ let merchant = state+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, key_store).await.change_context(AnalyticsError::UnknownError)?;@@ -1627,7 +1635,8 @@ pub async fn get_payment_response_hash_key(#[cfg(feature = "v2")]{let merchant_id = merchant_ids.first().ok_or(AnalyticsError::UnknownError)?;- let profiles = store+ let profiles = state+ .accounts_store.list_profile_by_merchant_id(key_store, merchant_id).await.change_context(AnalyticsError::UnknownError)?;diff --git a/crates/router/src/utils/connector_onboarding.rs b/crates/router/src/utils/connector_onboarding.rsindex d2c688abed..5c3c3ea0b8 100644--- a/crates/router/src/utils/connector_onboarding.rs+++ b/crates/router/src/utils/connector_onboarding.rs@@ -48,19 +48,17 @@ pub async fn check_if_connector_exists(merchant_id: &common_utils::id_type::MerchantId,profile_id: Option<common_utils::id_type::ProfileId>,) -> RouterResult<()> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(ApiErrorResponse::MerchantAccountNotFound)?;#[cfg(feature = "v1")]{let connector = state- .store+ .accounts_store.find_by_merchant_connector_account_merchant_id_merchant_connector_id(merchant_id,connector_id,diff --git a/crates/router/src/utils/user.rs b/crates/router/src/utils/user.rsindex 4b9d65d531..9eb5d21f75 100644--- a/crates/router/src/utils/user.rs+++ b/crates/router/src/utils/user.rs@@ -44,12 +44,10 @@ impl UserFromToken {&self,state: SessionState,) -> UserResult<MerchantAccount> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &self.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&self.merchant_id, &key_store_master_key).await.map_err(|e| {if e.current_context().is_db_not_found() {@@ -59,7 +57,7 @@ impl UserFromToken {}})?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&self.merchant_id, &key_store).await.map_err(|e| {diff --git a/crates/router/src/utils/user/dashboard_metadata.rs b/crates/router/src/utils/user/dashboard_metadata.rsindex 9a3d22b7e6..0701dd1a98 100644--- a/crates/router/src/utils/user/dashboard_metadata.rs+++ b/crates/router/src/utils/user/dashboard_metadata.rs@@ -48,7 +48,7 @@ pub async fn insert_merchant_scoped_metadata_to_db(.change_context(UserErrors::InternalServerError).attach_printable("Error Converting Struct To Serde Value")?;state- .store+ .accounts_store.insert_metadata(DashboardMetadataNew {user_id: None,merchant_id,@@ -82,7 +82,7 @@ pub async fn insert_user_scoped_metadata_to_db(.change_context(UserErrors::InternalServerError).attach_printable("Error Converting Struct To Serde Value")?;state- .store+ .accounts_store.insert_metadata(DashboardMetadataNew {user_id: Some(user_id.clone()),merchant_id,@@ -111,7 +111,7 @@ pub async fn get_merchant_scoped_metadata_from_db(metadata_keys: Vec<DBEnum>,) -> UserResult<Vec<DashboardMetadata>> {state- .store+ .accounts_store.find_merchant_scoped_dashboard_metadata(&merchant_id, &org_id, metadata_keys).await.change_context(UserErrors::InternalServerError)@@ -125,7 +125,7 @@ pub async fn get_user_scoped_metadata_from_db(metadata_keys: Vec<DBEnum>,) -> UserResult<Vec<DashboardMetadata>> {match state- .store+ .accounts_store.find_user_scoped_dashboard_metadata(&user_id, &merchant_id, &org_id, metadata_keys).await{@@ -152,7 +152,7 @@ pub async fn get_profile_user_scoped_metadata_from_db(let mut results = Vec::with_capacity(metadata_keys.len());for key in metadata_keys {if let Some(metadata) = state- .store+ .accounts_store.find_profile_scoped_dashboard_metadata(&user_id,&merchant_id,@@ -183,7 +183,7 @@ pub async fn update_merchant_scoped_metadata(.attach_printable("Error Converting Struct To Serde Value")?;state- .store+ .accounts_store.update_metadata(None,merchant_id,@@ -212,7 +212,7 @@ pub async fn update_user_scoped_metadata(.attach_printable("Error Converting Struct To Serde Value")?;state- .store+ .accounts_store.update_metadata(Some(user_id.clone()),merchant_id,@@ -399,7 +399,7 @@ where{let existing = {state- .store+ .accounts_store.find_profile_scoped_dashboard_metadata(&user.user_id,&user.merchant_id,@@ -426,7 +426,7 @@ wherematch existing {Some(metadata) => state- .store+ .accounts_store.update_metadata(metadata.user_id,metadata.merchant_id,@@ -445,7 +445,7 @@ whereNone => {let now = common_utils::date_time::now();state- .store+ .accounts_store.insert_metadata(DashboardMetadataNew {user_id: Some(user.user_id.clone()),merchant_id: user.merchant_id,diff --git a/crates/router/src/utils/user/sample_data.rs b/crates/router/src/utils/user/sample_data.rsindex 06668dbaa2..5953db61b2 100644--- a/crates/router/src/utils/user/sample_data.rs+++ b/crates/router/src/utils/user/sample_data.rs@@ -43,17 +43,15 @@ pub async fn generate_sample_data(return Err(SampleDataError::InvalidRange.into());}+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.change_context(SampleDataError::InternalServerError)?;let merchant_from_db = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, &key_store).await.change_context::<SampleDataError>(SampleDataError::DataDoesNotExist)?;@@ -81,7 +79,7 @@ pub async fn generate_sample_data(business_label_default.as_ref(),platform.get_processor(),req.profile_id.as_ref(),- &*state.store,+ state.accounts_store.as_ref(),).await.map(|business_profile| business_profile.get_id().to_owned());@@ -107,7 +105,7 @@ pub async fn generate_sample_data();state- .store+ .accounts_store.list_profile_by_merchant_id(platform.get_processor().get_key_store(), merchant_id).await.change_context(SampleDataError::InternalServerError)diff --git a/crates/router/src/utils/user/theme.rs b/crates/router/src/utils/user/theme.rsindex 423300b96d..1f56b9e1b1 100644--- a/crates/router/src/utils/user/theme.rs+++ b/crates/router/src/utils/user/theme.rs@@ -170,7 +170,8 @@ fn validate_tenant(state: &SessionState, tenant_id: &id_type::TenantId) -> UserRasync fn validate_org(state: &SessionState, org_id: &id_type::OrganizationId) -> UserResult<()> {state- .track_accounts_query(|db| db.find_organization_by_org_id(org_id))+ .accounts_store+ .find_organization_by_org_id(org_id).await.to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string())).map(|_| ())@@ -181,17 +182,15 @@ async fn validate_merchant_and_get_key_store(org_id: &id_type::OrganizationId,merchant_id: &id_type::MerchantId,) -> UserResult<MerchantKeyStore> {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?;let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(merchant_id, &key_store).await.to_not_found_response(UserErrors::InvalidThemeLineage("merchant_id".to_string()))?;@@ -220,7 +219,7 @@ async fn validate_profile(key_store: &MerchantKeyStore,) -> UserResult<()> {state- .store+ .accounts_store.find_business_profile_by_merchant_id_profile_id(key_store, merchant_id, profile_id).await.to_not_found_response(UserErrors::InvalidThemeLineage("profile_id".to_string()))diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rsindex 735548059f..af6f10bfcb 100644--- a/crates/router/src/utils/user_role.rs+++ b/crates/router/src/utils/user_role.rs@@ -243,7 +243,7 @@ pub async fn get_single_org_id(.ok_or(UserErrors::InternalServerError)?;match entity_type {EntityType::Tenant => Ok(state- .store+ .accounts_store.list_merchant_and_org_ids(1, None).await.change_context(UserErrors::InternalServerError)@@ -270,7 +270,7 @@ pub async fn get_single_merchant_id(.ok_or(UserErrors::InternalServerError)?;match entity_type {EntityType::Tenant | EntityType::Organization => Ok(state- .store+ .accounts_store.list_merchant_accounts_by_organization_id(org_id).await.to_not_found_response(UserErrors::InvalidRoleOperationWithMessage(@@ -299,17 +299,15 @@ pub async fn get_single_profile_id(.ok_or(UserErrors::InternalServerError)?;match entity_type {EntityType::Tenant | EntityType::Organization | EntityType::Merchant => {+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await.change_context(UserErrors::InternalServerError)?;Ok(state- .store+ .accounts_store.list_profile_by_merchant_id(&key_store, merchant_id).await.change_context(UserErrors::InternalServerError)?@@ -640,27 +638,26 @@ pub async fn send_role_deletion_email_using_db(.unwrap_or(state.conf.theme.email_config.clone());let org = state- .track_accounts_query(|db| db.find_organization_by_org_id(&user_from_token.org_id))+ .accounts_store+ .find_organization_by_org_id(&user_from_token.org_id).await.change_context(UserErrors::InternalServerError)?;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let merchant_key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &user_from_token.merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&user_from_token.merchant_id, &key_store_master_key).await.change_context(UserErrors::InternalServerError)?;let merchant = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&user_from_token.merchant_id, &merchant_key_store).await.change_context(UserErrors::InternalServerError)?;let profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(&merchant_key_store, &user_from_token.profile_id).await.change_context(UserErrors::InternalServerError)?;diff --git a/crates/router/src/workflows/api_key_expiry.rs b/crates/router/src/workflows/api_key_expiry.rsindex e5a1ad4d12..e7d7f33f86 100644--- a/crates/router/src/workflows/api_key_expiry.rs+++ b/crates/router/src/workflows/api_key_expiry.rs@@ -31,15 +31,17 @@ impl ProcessTrackerWorkflow<SessionState> for ApiKeyExpiryWorkflow {.tracking_data.clone().parse_value("ApiKeyExpiryTrackingData")?;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store+ .accounts_store.get_merchant_key_store_by_merchant_id(&tracking_data.merchant_id,- &state.store.get_master_key().to_vec().into(),+ &key_store_master_key,).await?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store).await?;diff --git a/crates/router/src/workflows/attach_payout_account_workflow.rs b/crates/router/src/workflows/attach_payout_account_workflow.rsindex 7c7d19f56c..e22233b603 100644--- a/crates/router/src/workflows/attach_payout_account_workflow.rs+++ b/crates/router/src/workflows/attach_payout_account_workflow.rs@@ -36,14 +36,14 @@ impl ProcessTrackerWorkflow<SessionState> for AttachPayoutAccountWorkflow {.clone().get_required_value("merchant_id")?;- let key_store = db- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await?;diff --git a/crates/router/src/workflows/dispute_list.rs b/crates/router/src/workflows/dispute_list.rsindex be2cf8bfba..f58e10bd46 100644--- a/crates/router/src/workflows/dispute_list.rs+++ b/crates/router/src/workflows/dispute_list.rs@@ -45,13 +45,16 @@ impl ProcessTrackerWorkflow<SessionState> for DisputeListWorkflow {.clone().parse_value("ProcessDisputePTData")?;- let provider_key_store = db+ let key_store_master_key = db.get_master_key().to_vec().into();+ let provider_key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&tracking_data.merchant_id,- &db.get_master_key().to_vec().into(),+ &key_store_master_key,).await?;- let provider_account = db+ let provider_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &provider_key_store).await?;@@ -59,14 +62,14 @@ impl ProcessTrackerWorkflow<SessionState> for DisputeListWorkflow {.processor_merchant_id.as_ref().unwrap_or(&tracking_data.merchant_id);- let processor_key_store = db- .get_merchant_key_store_by_merchant_id(- processor_merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let processor_key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(processor_merchant_id, &key_store_master_key).await?;- let processor_account = db+ let processor_account = state+ .accounts_store.find_merchant_account_by_merchant_id(processor_merchant_id, &processor_key_store).await?;@@ -79,7 +82,7 @@ impl ProcessTrackerWorkflow<SessionState> for DisputeListWorkflow {);let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&tracking_data.profile_id,diff --git a/crates/router/src/workflows/network_tokenization.rs b/crates/router/src/workflows/network_tokenization.rsindex 7daf746c3d..95d46b9761 100644--- a/crates/router/src/workflows/network_tokenization.rs+++ b/crates/router/src/workflows/network_tokenization.rs@@ -85,8 +85,10 @@ async fn generate_network_token(let db = &*state.store;let merchant_id = tracking_data.merchant_id.clone();- let key_store = db- .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.inspect_err(|error| {logger::error!(@@ -96,7 +98,8 @@ async fn generate_network_token();})?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.inspect_err(|error| {@@ -107,7 +110,8 @@ async fn generate_network_token();})?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&merchant_id,@@ -195,8 +199,10 @@ async fn generate_network_token(let db = &*state.store;let merchant_id = tracking_data.merchant_id.clone();- let key_store = db- .get_merchant_key_store_by_merchant_id(&merchant_id, &db.get_master_key().to_vec().into())+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.inspect_err(|error| {logger::error!(@@ -206,7 +212,8 @@ async fn generate_network_token();})?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.inspect_err(|error| {@@ -217,7 +224,8 @@ async fn generate_network_token();})?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_merchant_id_profile_id(&key_store,&merchant_id,diff --git a/crates/router/src/workflows/outgoing_webhook_retry.rs b/crates/router/src/workflows/outgoing_webhook_retry.rsindex ebaef7ceff..853baab8cb 100644--- a/crates/router/src/workflows/outgoing_webhook_retry.rs+++ b/crates/router/src/workflows/outgoing_webhook_retry.rs@@ -76,10 +76,12 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {}});- let webhook_key_store = db+ let webhook_key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&webhook_recipient_merchant_id, master_key).await?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(&webhook_key_store,&tracking_data.business_profile_id,@@ -169,10 +171,12 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {// Event inserted by an older version of the application, or event created when sending webhooks to a connectorNone => {// Fetch provider merchant account and keystore- let provider_key_store = db+ let provider_key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&provider_merchant_id, master_key).await?;- let provider_account = db+ let provider_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&provider_merchant_id,&provider_key_store,@@ -185,10 +189,12 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {{(provider_account.clone(), provider_key_store.clone())} else {- let processor_key_store = db+ let processor_key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&processor_merchant_id, master_key).await?;- let processor_account = db+ let processor_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&processor_merchant_id,&processor_key_store,@@ -326,10 +332,12 @@ impl ProcessTrackerWorkflow<SessionState> for OutgoingWebhookRetryWorkflow {.clone().unwrap_or_else(|| tracking_data.merchant_id.clone());- let webhook_key_store = db+ let webhook_key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&webhook_recipient_merchant_id, master_key).await?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(&webhook_key_store,&tracking_data.business_profile_id,diff --git a/crates/router/src/workflows/payment_method_modular_backward_compat.rs b/crates/router/src/workflows/payment_method_modular_backward_compat.rsindex ffe7a15559..dbadb6e4ec 100644--- a/crates/router/src/workflows/payment_method_modular_backward_compat.rs+++ b/crates/router/src/workflows/payment_method_modular_backward_compat.rs@@ -817,15 +817,14 @@ pub async fn run_payment_method_modular_backward_compat_backfill(let db = &*state.store;let workflow = BackwardCompatWorkflowBuilder::new().load_tracking_data(tracking_data);let merchant_id = workflow.merchant_id()?.clone();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await?;let workflow = workflow.load_context(key_store, merchant_account);diff --git a/crates/router/src/workflows/payment_method_modular_forward_compat.rs b/crates/router/src/workflows/payment_method_modular_forward_compat.rsindex 5ae1471ba6..b13ada6d43 100644--- a/crates/router/src/workflows/payment_method_modular_forward_compat.rs+++ b/crates/router/src/workflows/payment_method_modular_forward_compat.rs@@ -524,15 +524,14 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodModularForwardCompatWlet workflow = ForwardCompatWorkflowBuilder::new().load_tracking_data(tracking_data);let merchant_id = workflow.merchant_id()?.clone();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await?;let workflow = workflow.load_context(key_store, merchant_account);diff --git a/crates/router/src/workflows/payment_method_status_update.rs b/crates/router/src/workflows/payment_method_status_update.rsindex 185a886f76..4680462923 100644--- a/crates/router/src/workflows/payment_method_status_update.rs+++ b/crates/router/src/workflows/payment_method_status_update.rs@@ -32,15 +32,14 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentMethodStatusUpdateWorkflowlet curr_pm_status = tracking_data.curr_status;let merchant_id = tracking_data.merchant_id;let last_modified_by = tracking_data.last_modified_by;+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await?;diff --git a/crates/router/src/workflows/payment_sync.rs b/crates/router/src/workflows/payment_sync.rsindex be644273c5..da015fcb7b 100644--- a/crates/router/src/workflows/payment_sync.rs+++ b/crates/router/src/workflows/payment_sync.rs@@ -53,24 +53,19 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {.tracking_data.clone().parse_value("PaymentsRetrieveRequest")?;- let key_store = db- .get_merchant_key_store_by_merchant_id(- tracking_data- .merchant_id- .as_ref()- .get_required_value("merchant_id")?,- &db.get_master_key().to_vec().into(),- )+ let merchant_id = tracking_data+ .merchant_id+ .as_ref()+ .get_required_value("merchant_id")?;+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key).await?;- let merchant_account = db- .find_merchant_account_by_merchant_id(- tracking_data- .merchant_id- .as_ref()- .get_required_value("merchant_id")?,- &key_store,- )+ let merchant_account = state+ .accounts_store+ .find_merchant_account_by_merchant_id(merchant_id, &key_store).await?;let platform = domain::Platform::new(@@ -214,7 +209,8 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsSyncWorkflow {.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Could not find profile_id in payment intent")?;- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(&key_store, profile_id).await.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {diff --git a/crates/router/src/workflows/payout_sync.rs b/crates/router/src/workflows/payout_sync.rsindex 6ce418a4ac..2a11d5c266 100644--- a/crates/router/src/workflows/payout_sync.rs+++ b/crates/router/src/workflows/payout_sync.rs@@ -53,14 +53,14 @@ impl ProcessTrackerWorkflow<SessionState> for PayoutSyncWorkFlow {.merchant_id.clone().get_required_value("merchant_id")?;- let key_store = db- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await?;@@ -262,7 +262,6 @@ impl PayoutSyncWorkFlow {platform: &domain::Platform,process: storage::ProcessTracker,) -> Result<(), errors::ProcessTrackerError> {- let db = &*state.store;state.store.as_scheduler()@@ -271,7 +270,8 @@ impl PayoutSyncWorkFlow {let event_type: Option<enums::EventType> = payout_data.payout_attempt.status.into();- let business_profile = db+ let business_profile = state+ .accounts_store.find_business_profile_by_profile_id(key_store, &payout_data.profile_id).await.map_err(errors::ProcessTrackerError::EStorageError)?;diff --git a/crates/router/src/workflows/post_capture_void_sync.rs b/crates/router/src/workflows/post_capture_void_sync.rsindex fc0f90b31e..6d17612723 100644--- a/crates/router/src/workflows/post_capture_void_sync.rs+++ b/crates/router/src/workflows/post_capture_void_sync.rs@@ -46,14 +46,17 @@ impl ProcessTrackerWorkflow<SessionState> for PaymentsPostCaptureVoidSyncWorkflo.tracking_data.clone().parse_value("PaymentsPostCaptureVoidSyncTrackingData")?;- let key_store = db+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&tracking_data.merchant_id,- &db.get_master_key().to_vec().into(),+ &key_store_master_key,).await?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store).await?;diff --git a/crates/router/src/workflows/process_dispute.rs b/crates/router/src/workflows/process_dispute.rsindex 33f5213f06..92497262c4 100644--- a/crates/router/src/workflows/process_dispute.rs+++ b/crates/router/src/workflows/process_dispute.rs@@ -42,13 +42,16 @@ impl ProcessTrackerWorkflow<SessionState> for ProcessDisputeWorkflow {.clone().parse_value("ProcessDisputePTData")?;- let provider_key_store = db+ let key_store_master_key = db.get_master_key().to_vec().into();+ let provider_key_store = state+ .accounts_store.get_merchant_key_store_by_merchant_id(&tracking_data.merchant_id,- &db.get_master_key().to_vec().into(),+ &key_store_master_key,).await?;- let provider_account = db+ let provider_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &provider_key_store).await?;@@ -56,13 +59,13 @@ impl ProcessTrackerWorkflow<SessionState> for ProcessDisputeWorkflow {.processor_merchant_id.as_ref().unwrap_or(&tracking_data.merchant_id);- let processor_key_store = db- .get_merchant_key_store_by_merchant_id(- processor_merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let processor_key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(processor_merchant_id, &key_store_master_key).await?;- let processor_account = db+ let processor_account = state+ .accounts_store.find_merchant_account_by_merchant_id(processor_merchant_id, &processor_key_store).await?;@@ -82,7 +85,7 @@ impl ProcessTrackerWorkflow<SessionState> for ProcessDisputeWorkflow {.await?;let business_profile = state- .store+ .accounts_store.find_business_profile_by_profile_id(platform.get_processor().get_key_store(),&payment_attempt.profile_id,diff --git a/crates/router/src/workflows/revenue_recovery.rs b/crates/router/src/workflows/revenue_recovery.rsindex b1e986e3eb..076e3ca759 100644--- a/crates/router/src/workflows/revenue_recovery.rs+++ b/crates/router/src/workflows/revenue_recovery.rs@@ -205,22 +205,24 @@ pub(crate) async fn extract_data_and_perform_action() -> Result<pcr_storage_types::RevenueRecoveryPaymentData, errors::ProcessTrackerError> {let db = &state.store;- let key_store = db- .get_merchant_key_store_by_merchant_id(- &tracking_data.merchant_id,- &db.get_master_key().to_vec().into(),- )+ let key_store_master_key = db.get_master_key().to_vec().into();+ let key_store = state+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&tracking_data.merchant_id, &key_store_master_key).await?;- let merchant_account = db+ let merchant_account = state+ .accounts_store.find_merchant_account_by_merchant_id(&tracking_data.merchant_id, &key_store).await?;- let profile = db+ let profile = state+ .accounts_store.find_business_profile_by_profile_id(&key_store, &tracking_data.profile_id).await?;- let billing_mca = db+ let billing_mca = state+ .accounts_store.find_merchant_connector_account_by_id(&tracking_data.billing_mca_id, &key_store).await?;diff --git a/crates/router/tests/payments.rs b/crates/router/tests/payments.rsindex a9fdb532b6..9af5eb6b4a 100644--- a/crates/router/tests/payments.rs+++ b/crates/router/tests/payments.rs@@ -296,17 +296,15 @@ async fn payments_create_core() {|| {},).unwrap();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.unwrap();let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.unwrap();@@ -619,17 +617,15 @@ async fn payments_create_core_adyen_no_redirect() {let customer_id = format!("cust_{}", common_utils::generate_uuid_v4());let merchant_id = id_type::MerchantId::try_from(Cow::from("juspay_merchant")).unwrap();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.unwrap();let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.unwrap();diff --git a/crates/router/tests/payments2.rs b/crates/router/tests/payments2.rsindex cfef8de8b0..378e26b996 100644--- a/crates/router/tests/payments2.rs+++ b/crates/router/tests/payments2.rs@@ -56,17 +56,15 @@ async fn payments_create_core() {|| {},).unwrap();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.unwrap();let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.unwrap();@@ -387,17 +385,15 @@ async fn payments_create_core_adyen_no_redirect() {let payment_id =id_type::PaymentId::try_from(Cow::Borrowed("pay_mbabizu24mvu3mela5njyhpit10")).unwrap();+ let key_store_master_key = state.store.get_master_key().to_vec().into();let key_store = state- .store- .get_merchant_key_store_by_merchant_id(- &merchant_id,- &state.store.get_master_key().to_vec().into(),- )+ .accounts_store+ .get_merchant_key_store_by_merchant_id(&merchant_id, &key_store_master_key).await.unwrap();let merchant_account = state- .store+ .accounts_store.find_merchant_account_by_merchant_id(&merchant_id, &key_store).await.unwrap();diff --git a/crates/router_derive/Cargo.toml b/crates/router_derive/Cargo.tomlindex 45d437ec5d..705833be06 100644--- a/crates/router_derive/Cargo.toml+++ b/crates/router_derive/Cargo.toml@@ -17,9 +17,10 @@ proc-macro2 = "1.0.95"quote = "1.0.40"serde_json = "1.0.140"strum = { version = "0.26.3", features = ["derive"] }-syn = { version = "2.0.101", features = ["full", "extra-traits"] } # the full feature does not seem to encompass all the features+syn = { version = "2.0.101", features = ["full", "extra-traits", "visit-mut"] } # the full feature does not seem to encompass all the features[dev-dependencies]+async-trait = "0.1.92"error-stack = "0.4.1"serde = { version = "1.0.219", features = ["derive"] }serde_json = "1.0.140"@@ -27,6 +28,7 @@ url = { version = "2.5.4", features = ["serde"] }utoipa = "4.2.3"common_utils = { version = "0.1.0", path = "../common_utils" }+router_env = { version = "0.1.0", path = "../router_env" }[lints]workspace = truediff --git a/crates/router_derive/src/lib.rs b/crates/router_derive/src/lib.rsindex e1fff32163..df1bb1db38 100644--- a/crates/router_derive/src/lib.rs+++ b/crates/router_derive/src/lib.rs@@ -5,6 +5,27 @@ use syn::parse_macro_input;use crate::macros::diesel::DieselEnumMeta;mod macros;+/// Generate a caller-tracked interface and blanket implementation for an async trait.+///+/// The original trait remains available to its existing implementations. The generated+/// `Tracked*` trait exposes methods that capture the call site before their futures run.+#[proc_macro_attribute]+pub fn track_async_interface(+ args: proc_macro::TokenStream,+ item: proc_macro::TokenStream,+) -> proc_macro::TokenStream {+ if !args.is_empty() {+ return syn::Error::new(proc_macro2::Span::call_site(), "no arguments are supported")+ .to_compile_error()+ .into();+ }++ let item = parse_macro_input!(item as syn::ItemTrait);+ macros::track_async_interface::track_async_interface(item)+ .unwrap_or_else(|error| error.to_compile_error())+ .into()+}+/// Uses the [`Debug`][Debug] implementation of a type to derive its [`Display`][Display]/// implementation.///diff --git a/crates/router_derive/src/macros.rs b/crates/router_derive/src/macros.rsindex 74a9bdd66d..fa9643ae0a 100644--- a/crates/router_derive/src/macros.rs+++ b/crates/router_derive/src/macros.rs@@ -8,6 +8,7 @@ pub(crate) mod misc;pub(crate) mod operation;pub(crate) mod schema;pub(crate) mod to_encryptable;+pub(crate) mod track_async_interface;pub(crate) mod try_get_enum;pub(crate) mod xss_validation;diff --git a/crates/router_derive/src/macros/track_async_interface.rs b/crates/router_derive/src/macros/track_async_interface.rsnew file mode 100644index 0000000000..00d066726b--- /dev/null+++ b/crates/router_derive/src/macros/track_async_interface.rs@@ -0,0 +1,168 @@+use proc_macro2::TokenStream;+use quote::{format_ident, quote};+use syn::{visit_mut::VisitMut, FnArg, ItemTrait, Pat, ReturnType, TraitItem};++struct BindReferenceLifetimes(syn::Lifetime);++impl VisitMut for BindReferenceLifetimes {+ fn visit_type_reference_mut(&mut self, reference: &mut syn::TypeReference) {+ if reference+ .lifetime+ .as_ref()+ .is_none_or(|lifetime| lifetime.ident == "_")+ {+ reference.lifetime = Some(self.0.clone());+ }+ syn::visit_mut::visit_type_reference_mut(self, reference);+ }+}++/// Generate a caller-tracked interface from an async trait without changing its implementations.+pub(crate) fn track_async_interface(item: ItemTrait) -> syn::Result<TokenStream> {+ let raw_name = item.ident.clone();+ let tracked_name = format_ident!("Tracked{raw_name}");+ let visibility = item.vis.clone();+ let tracked_lifetime = syn::Lifetime::new("'__tracked", proc_macro2::Span::call_site());+ let cfg_attrs: Vec<_> = item+ .attrs+ .iter()+ .filter(|attr| attr.path().is_ident("cfg") || attr.path().is_ident("cfg_attr"))+ .collect();++ let mut tracked_methods = Vec::new();+ let mut implementations = Vec::new();+ let mut has_error_type = false;++ for trait_item in &item.items {+ let TraitItem::Fn(method) = trait_item else {+ if let TraitItem::Type(associated_type) = trait_item {+ if associated_type.ident == "Error" {+ has_error_type = true;+ continue;+ }+ }+ return Err(syn::Error::new_spanned(+ trait_item,+ "only async methods and the Error associated type are supported",+ ));+ };++ let signature = &method.sig;+ if signature.asyncness.is_none()+ || !signature.generics.params.is_empty()+ || signature.generics.where_clause.is_some()+ || method.default.is_some()+ {+ return Err(syn::Error::new_spanned(+ signature,+ "tracked interface methods must be async, non-generic, and required",+ ));+ }++ let ReturnType::Type(_, output) = &signature.output else {+ return Err(syn::Error::new_spanned(+ signature,+ "tracked interface methods must have a return type",+ ));+ };++ let mut inputs = signature.inputs.clone();+ let mut arguments = Vec::new();+ let mut has_receiver = false;+ for input in &mut inputs {+ match input {+ FnArg::Receiver(receiver) => {+ has_receiver = true;+ let Some((_, lifetime)) = &mut receiver.reference else {+ return Err(syn::Error::new_spanned(+ receiver,+ "tracked interface methods must take &self",+ ));+ };+ if lifetime.is_some() {+ return Err(syn::Error::new_spanned(+ receiver,+ "explicit receiver lifetimes are not supported",+ ));+ }+ *lifetime = Some(tracked_lifetime.clone());+ arguments.push(quote!(self));+ }+ FnArg::Typed(argument) => {+ BindReferenceLifetimes(tracked_lifetime.clone())+ .visit_type_mut(&mut argument.ty);+ let Pat::Ident(identifier) = argument.pat.as_ref() else {+ return Err(syn::Error::new_spanned(+ &argument.pat,+ "tracked interface arguments must be identifiers",+ ));+ };+ let name = &identifier.ident;+ arguments.push(quote!(#name));+ }+ }+ }+ if !has_receiver {+ return Err(syn::Error::new_spanned(+ signature,+ "tracked interface methods must take &self",+ ));+ }++ let method_name = &signature.ident;+ let attributes = &method.attrs;+ let future_output = quote!(+ ::std::pin::Pin<+ ::std::boxed::Box<+ dyn ::std::future::Future<Output = #output> + Send + #tracked_lifetime+ >+ >+ );++ tracked_methods.push(quote! {+ #(#attributes)*+ #[track_caller]+ fn #method_name<#tracked_lifetime>(#inputs) -> #future_output;+ });+ implementations.push(quote! {+ #(#attributes)*+ #[track_caller]+ fn #method_name<#tracked_lifetime>(#inputs) -> #future_output {+ let caller = ::std::panic::Location::caller();+ ::std::boxed::Box::pin(router_env::call_origin::with_origin(+ caller,+ <T as #raw_name>::#method_name(#(#arguments),*),+ ))+ }+ });+ }++ // Keep the original trait available to existing store implementations. The generated+ // interface deliberately does not inherit it, so trait objects expose only tracked calls.+ let tracked_error_type = has_error_type.then(|| {+ quote!(+ type Error;+ )+ });+ let implemented_error_type =+ has_error_type.then(|| quote!(type Error = <T as #raw_name>::Error;));++ Ok(quote! {+ #item++ #(#cfg_attrs)*+ #visibility trait #tracked_name: Send + Sync {+ #tracked_error_type+ #(#tracked_methods)*+ }++ #(#cfg_attrs)*+ impl<T> #tracked_name for T+ where+ T: #raw_name + Send + Sync + ?Sized,+ {+ #implemented_error_type+ #(#implementations)*+ }+ })+}diff --git a/crates/router_derive/tests/track_async_interface.rs b/crates/router_derive/tests/track_async_interface.rsnew file mode 100644index 0000000000..9cd3a222eb--- /dev/null+++ b/crates/router_derive/tests/track_async_interface.rs@@ -0,0 +1,103 @@+use std::{+ future::Future,+ panic::Location,+ task::{Context, Poll, Waker},+};++#[router_derive::track_async_interface]+#[async_trait::async_trait]+trait MerchantAccountInterface {+ type Error;++ async fn find(&self, id: &u32) -> Result<(u32, Option<u32>), Self::Error>;+}++struct Store;++#[router_derive::track_async_interface]+#[async_trait::async_trait]+trait OrganizationInterface {+ async fn find_organization(&self) -> Result<Option<u32>, ()>;++ async fn find_with_optional_id(+ &self,+ id: Option<&u32>,+ ) -> Result<(Option<u32>, Option<u32>), ()>;+}++trait AccountsStorageInterface:+ TrackedMerchantAccountInterface<Error = ()> + TrackedOrganizationInterface+{+}++impl AccountsStorageInterface for Store {}++#[async_trait::async_trait]+impl MerchantAccountInterface for Store {+ type Error = ();++ async fn find(&self, id: &u32) -> Result<(u32, Option<u32>), Self::Error> {+ Ok((+ *id,+ router_env::call_origin::current_origin().map(Location::line),+ ))+ }+}++#[async_trait::async_trait]+impl OrganizationInterface for Store {+ async fn find_organization(&self) -> Result<Option<u32>, ()> {+ Ok(router_env::call_origin::current_origin().map(Location::line))+ }++ async fn find_with_optional_id(+ &self,+ id: Option<&u32>,+ ) -> Result<(Option<u32>, Option<u32>), ()> {+ Ok((+ id.copied(),+ router_env::call_origin::current_origin().map(Location::line),+ ))+ }+}++#[allow(clippy::panic)]+fn poll_now<F: Future>(future: F) -> F::Output {+ let mut future = std::pin::pin!(future);+ let mut context = Context::from_waker(Waker::noop());+ let Poll::Ready(output) = future.as_mut().poll(&mut context) else {+ panic!("test future unexpectedly pending");+ };+ output+}++#[test]+fn tracked_trait_object_passes_the_call_site_to_the_raw_method() {+ let store: Box<dyn AccountsStorageInterface> = Box::new(Store);+ let id = 42;+ let expected_line = line!() + 1;+ let output = poll_now(store.find(&id));++ assert_eq!(output, Ok((id, Some(expected_line))));+ assert!(router_env::call_origin::current_origin().is_none());+}++#[test]+fn tracked_trait_without_error_type_passes_the_call_site() {+ let store: Box<dyn AccountsStorageInterface> = Box::new(Store);+ let expected_line = line!() + 1;+ let output = poll_now(store.find_organization());++ assert_eq!(output, Ok(Some(expected_line)));+ assert!(router_env::call_origin::current_origin().is_none());+}++#[test]+fn tracked_nested_reference_passes_the_call_site() {+ let store: Box<dyn AccountsStorageInterface> = Box::new(Store);+ let id = 42;+ let expected_line = line!() + 1;+ let output = poll_now(store.find_with_optional_id(Some(&id)));++ assert_eq!(output, Ok((Some(id), Some(expected_line))));+}diff --git a/crates/scheduler/Cargo.toml b/crates/scheduler/Cargo.tomlindex b4dc21025f..123dc5452c 100644--- a/crates/scheduler/Cargo.toml+++ b/crates/scheduler/Cargo.toml@@ -39,6 +39,7 @@ external_services = { version = "0.1.0", path = "../external_services" }hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false }redis_interface = { version = "0.1.0", path = "../redis_interface", default-features = false }router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] }+router_derive = { version = "0.1.0", path = "../router_derive" }storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false }[lints]diff --git a/crates/scheduler/src/consumer.rs b/crates/scheduler/src/consumer.rsindex 2cde84246f..c0a121fc5c 100644--- a/crates/scheduler/src/consumer.rs+++ b/crates/scheduler/src/consumer.rs@@ -23,8 +23,9 @@ use tokio::sync::mpsc;use super::env::logger;pub use super::workflows::ProcessTrackerWorkflow;use crate::{- configs::settings::SchedulerSettings, db::process_tracker::ProcessTrackerInterface, errors,- metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface, SchedulerSessionState,+ configs::settings::SchedulerSettings, db::process_tracker::TrackedProcessTrackerInterface,+ errors, metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface,+ SchedulerSessionState,};// Valid consumer business statuses@@ -231,7 +232,7 @@ pub async fn consumer_operations<T: SchedulerSessionState + 'static>(#[instrument(skip(db, redis_conn))]pub async fn fetch_consumer_tasks(- db: &dyn ProcessTrackerInterface,+ db: &dyn TrackedProcessTrackerInterface,redis_conn: &RedisConnectionWithContext,stream_name: &str,group_name: &str,@@ -354,7 +355,7 @@ pub async fn consumer_error_handler(}pub async fn create_task(- db: &dyn ProcessTrackerInterface,+ db: &dyn TrackedProcessTrackerInterface,process_tracker_entry: storage::ProcessTrackerNew,) -> CustomResult<(), storage_impl::errors::StorageError> {db.insert_process(process_tracker_entry).await?;diff --git a/crates/scheduler/src/db/process_tracker.rs b/crates/scheduler/src/db/process_tracker.rsindex de78c2fd40..67abee4abe 100644--- a/crates/scheduler/src/db/process_tracker.rs+++ b/crates/scheduler/src/db/process_tracker.rs@@ -7,6 +7,7 @@ use time::PrimitiveDateTime;use crate::{metrics, scheduler::Store};+#[router_derive::track_async_interface]#[async_trait::async_trait]pub trait ProcessTrackerInterface: Send + Sync + 'static {async fn reinitialize_limbo_processes(@@ -140,7 +141,8 @@ impl ProcessTrackerInterface for Store {this: storage::ProcessTracker,schedule_time: PrimitiveDateTime,) -> CustomResult<(), errors::StorageError> {- self.update_process(+ ProcessTrackerInterface::update_process(+ self,this,storage::ProcessTrackerUpdate::StatusRetryUpdate {status: storage_enums::ProcessTrackerStatus::New,@@ -159,7 +161,8 @@ impl ProcessTrackerInterface for Store {) -> CustomResult<(), errors::StorageError> {metrics::TASK_RETRIED.add(1, &[]);let retry_count = this.retry_count + 1;- self.update_process(+ ProcessTrackerInterface::update_process(+ self,this,storage::ProcessTrackerUpdate::StatusRetryUpdate {status: storage_enums::ProcessTrackerStatus::Pending,@@ -176,7 +179,8 @@ impl ProcessTrackerInterface for Store {this: storage::ProcessTracker,business_status: &'static str,) -> CustomResult<(), errors::StorageError> {- self.update_process(+ ProcessTrackerInterface::update_process(+ self,this,storage::ProcessTrackerUpdate::StatusUpdate {status: storage_enums::ProcessTrackerStatus::Finish,@@ -194,7 +198,7 @@ impl ProcessTrackerInterface for Store {this: storage::ProcessTracker,update: storage::ProcessTrackerUpdate,) -> CustomResult<(), errors::StorageError> {- self.update_process(this, update)+ ProcessTrackerInterface::update_process(self, this, update).await.attach_printable("Failed to finish process with update")?;metrics::TASK_FINISHED.add(1, &[]);diff --git a/crates/scheduler/src/scheduler.rs b/crates/scheduler/src/scheduler.rsindex 5fc67a565a..5e966afe48 100644--- a/crates/scheduler/src/scheduler.rs+++ b/crates/scheduler/src/scheduler.rs@@ -12,7 +12,7 @@ use super::env::logger::error;pub use crate::{configs::settings::SchedulerSettings,consumer::{self, workflows},- db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface},+ db::{process_tracker::TrackedProcessTrackerInterface, queue::QueueInterface},errors,flow::SchedulerFlow,producer,@@ -40,7 +40,7 @@ impl<T: SchedulerInterface> AsSchedulerInterface for T {#[async_trait::async_trait]pub trait SchedulerInterface:- ProcessTrackerInterface + QueueInterface + AsSchedulerInterface+ TrackedProcessTrackerInterface + QueueInterface + AsSchedulerInterface + 'static{}diff --git a/crates/storage_impl/src/business_profile.rs b/crates/storage_impl/src/business_profile.rsindex c30bfe28e5..2e5cc8d3c6 100644--- a/crates/storage_impl/src/business_profile.rs+++ b/crates/storage_impl/src/business_profile.rs@@ -21,9 +21,7 @@ use crate::redis::{};use crate::{behaviour::{Conversion, ForeignFrom, ReverseConversion},- kv_router_store,- utils::{pg_accounts_connection_read, pg_accounts_connection_write},- CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,+ kv_router_store, CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,};/// Cache key for a profile.@@ -185,7 +183,7 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {merchant_key_store: &MerchantKeyStore,business_profile: domain::Profile,) -> CustomResult<domain::Profile, StorageError> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;Box::pin(business_profile.construct_new()@@ -212,7 +210,7 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {profile_id: &common_utils::id_type::ProfileId,) -> CustomResult<domain::Profile, StorageError> {let fetch_func = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;diesel::Profile::find_by_merchant_id_profile_id(&conn,&merchant_key_store.merchant_id,@@ -272,7 +270,7 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {profile_id: &common_utils::id_type::ProfileId,) -> CustomResult<domain::Profile, StorageError> {let fetch_func = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;diesel::Profile::find_by_merchant_id_profile_id(&conn, merchant_id, profile_id).await.map_err(|error| report!(StorageError::from(error)))@@ -318,7 +316,7 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {profile_name: &str,merchant_id: &common_utils::id_type::MerchantId,) -> CustomResult<domain::Profile, StorageError> {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;self.call_database_new(merchant_key_store,diesel::Profile::find_by_profile_name_merchant_id(&conn, profile_name, merchant_id),@@ -333,7 +331,7 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {current_state: domain::Profile,profile_update: domain::ProfileUpdate,) -> CustomResult<domain::Profile, StorageError> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let updated_profile = Box::pin(Conversion::convert(current_state).await@@ -363,7 +361,7 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {profile_id: &common_utils::id_type::ProfileId,merchant_id: &common_utils::id_type::MerchantId,) -> CustomResult<bool, StorageError> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let is_deleted =diesel::Profile::delete_by_profile_id_merchant_id(&conn, profile_id, merchant_id).await@@ -381,7 +379,7 @@ impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {merchant_key_store: &MerchantKeyStore,merchant_id: &common_utils::id_type::MerchantId,) -> CustomResult<Vec<domain::Profile>, StorageError> {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;Box::pin(self.find_resources_new(merchant_key_store,diesel::Profile::list_profile_by_merchant_id(&conn, merchant_id),diff --git a/crates/storage_impl/src/database/store.rs b/crates/storage_impl/src/database/store.rsindex 40ba24f43b..76020669e2 100644--- a/crates/storage_impl/src/database/store.rs+++ b/crates/storage_impl/src/database/store.rs@@ -5,6 +5,7 @@ use bb8::CustomizeConnection;use common_utils::{external_service::{ExternalServiceEventEmitter, NoOpEventEmitter},id_type,+ request_context::RequestContext,types::{keymanager, TenantConfig},DbConnectionParams,};@@ -15,6 +16,7 @@ use error_stack::ResultExt;use crate::{config::Database,errors::{StorageError, StorageResult},+ metrics,};pub type RawPgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<DejaPgConnection>>;@@ -53,9 +55,9 @@ impl PgPool {/// Shared database-pool ownership.///-/// Request context is intentionally not part of this trait. Request-scoped wrappers such as-/// `RouterStore` and `KVRouterStore` implement `RequestContext` separately, and the connection-/// helpers in `crate::connection` combine the two when leasing a connection.+/// Request-scoped wrappers such as `RouterStore` and `KVRouterStore` implement+/// `RequestContext` separately. Connection helpers require that context when leasing+/// a connection, while pool-only stores can implement this trait without it.#[async_trait::async_trait]pub trait DatabaseStore: Clone + Send + Sync {type Config: Send;@@ -71,6 +73,81 @@ pub trait DatabaseStore: Clone + Send + Sync {fn get_accounts_master_pool(&self) -> &PgPool;fn get_accounts_replica_pool(&self) -> &PgPool;+ /// Lease an accounts read connection with request and read-ledger context.+ async fn pg_accounts_connection_read(&self) -> StorageResult<DatabaseConnectionWithContext<'_>>+ where+ Self: RequestContext,+ {+ // If only OLAP is enabled, get the replica pool.+ #[cfg(all(feature = "olap", not(feature = "oltp")))]+ let (pool, db_pool_label) = (+ self.get_accounts_replica_pool(),+ super::pool_metrics::DbPool::AccountsReplica,+ );++ // If either one of these is true, get the master pool:+ // 1. Only OLTP is enabled.+ // 2. Both OLAP and OLTP are enabled.+ // 3. Both OLAP and OLTP are disabled.+ #[cfg(any(+ all(not(feature = "olap"), feature = "oltp"),+ all(feature = "olap", feature = "oltp"),+ all(not(feature = "olap"), not(feature = "oltp"))+ ))]+ let (pool, db_pool_label) = (+ self.get_accounts_master_pool(),+ super::pool_metrics::DbPool::AccountsMaster,+ );+ let tenant_id = pool.tenant_id.get_string_repr();++ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut connection = metrics::record_db_connection_acquire_duration(+ pool.pg_pool.get(),+ db_pool_label,+ tenant_id,+ )+ .await+ .change_context(StorageError::DatabaseConnectionError)?;++ #[cfg(feature = "deja")]+ crate::utils::deja_route_replay_schema(&mut connection, self).await;++ Ok(DatabaseConnectionWithContext::new(+ connection,+ self.request_id().map(str::to_owned),+ pool.event_emitter.clone(),+ self.read_ledger().cloned(),+ ))+ }++ /// Lease an accounts-master write connection with request and read-ledger context.+ async fn pg_accounts_connection_write(&self) -> StorageResult<DatabaseConnectionWithContext<'_>>+ where+ Self: RequestContext,+ {+ let pool = self.get_accounts_master_pool();+ let tenant_id = pool.tenant_id.get_string_repr();++ #[cfg_attr(not(feature = "deja"), allow(unused_mut))]+ let mut connection = metrics::record_db_connection_acquire_duration(+ pool.pg_pool.get(),+ super::pool_metrics::DbPool::AccountsMaster,+ tenant_id,+ )+ .await+ .change_context(StorageError::DatabaseConnectionError)?;++ #[cfg(feature = "deja")]+ crate::utils::deja_route_replay_schema(&mut connection, self).await;++ Ok(DatabaseConnectionWithContext::new(+ connection,+ self.request_id().map(str::to_owned),+ pool.event_emitter.clone(),+ self.read_ledger().cloned(),+ ))+ }+/// Request correlation used by deja replay to route database connections to/// the active replay schema. Stores without request identity return `None`.#[cfg(feature = "deja")]diff --git a/crates/storage_impl/src/hierarchical_resource.rs b/crates/storage_impl/src/hierarchical_resource.rsindex 44653cf405..0a75aea2ec 100644--- a/crates/storage_impl/src/hierarchical_resource.rs+++ b/crates/storage_impl/src/hierarchical_resource.rs@@ -7,11 +7,7 @@ use hyperswitch_domain_models::{use hyperswitch_masking::Secret;use router_env::instrument;-use crate::{- kv_router_store,- utils::{pg_accounts_connection_read, pg_accounts_connection_write},- CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,-};+use crate::{kv_router_store, CustomResult, DatabaseStore, MockDb, RouterStore, StorageError};#[async_trait::async_trait]impl<T: DatabaseStore> HierarchicalResourceInterface for kv_router_store::KVRouterStore<T> {@@ -80,7 +76,7 @@ impl<T: DatabaseStore> HierarchicalResourceInterface for RouterStore<T> {resource: domain::HierarchicalResource,key: &Secret<Vec<u8>>,) -> CustomResult<domain::HierarchicalResource, Self::Error> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let identifier = resource.key_identifier().change_context(Self::Error::EncryptionError)?;@@ -107,7 +103,7 @@ impl<T: DatabaseStore> HierarchicalResourceInterface for RouterStore<T> {id: common_utils::id_type::ResourceId,key: &Secret<Vec<u8>>,) -> CustomResult<domain::HierarchicalResource, Self::Error> {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;let resource =diesel_models::hierarchical_resource::HierarchicalResource::find_by_id(&conn, id).await@@ -131,7 +127,7 @@ impl<T: DatabaseStore> HierarchicalResourceInterface for RouterStore<T> {&self,id: common_utils::id_type::ResourceId,) -> CustomResult<String, Self::Error> {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;diesel_models::hierarchical_resource::HierarchicalResource::find_by_id(&conn, id).await.map(|resource| resource.scope_id)@@ -145,7 +141,7 @@ impl<T: DatabaseStore> HierarchicalResourceInterface for RouterStore<T> {resource_type: String,key: &Secret<Vec<u8>>,) -> CustomResult<Vec<domain::HierarchicalResource>, Self::Error> {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;let resources = diesel_models::hierarchical_resource::HierarchicalResource::list_by_scope_id_and_resource_type(&conn,scope_id,@@ -177,7 +173,7 @@ impl<T: DatabaseStore> HierarchicalResourceInterface for RouterStore<T> {update: domain::HierarchicalResourceDataUpdate,key: &Secret<Vec<u8>>,) -> CustomResult<domain::HierarchicalResource, Self::Error> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let resource = diesel_models::hierarchical_resource::HierarchicalResource::update_by_id(&conn,id,diff --git a/crates/storage_impl/src/merchant_account.rs b/crates/storage_impl/src/merchant_account.rsindex cfa7a4ea56..34fc2417b7 100644--- a/crates/storage_impl/src/merchant_account.rs+++ b/crates/storage_impl/src/merchant_account.rs@@ -23,7 +23,6 @@ use crate::{behaviour::{Conversion, ForeignFrom, ForeignInto, ReverseConversion},kv_router_store,store::MerchantAccountUpdateInternal,- utils::{pg_accounts_connection_read, pg_accounts_connection_write},CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,};@@ -155,7 +154,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {merchant_account: domain::MerchantAccount,merchant_key_store: &MerchantKeyStore,) -> CustomResult<domain::MerchantAccount, StorageError> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;merchant_account.construct_new().await@@ -180,7 +179,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {merchant_key_store: &MerchantKeyStore,) -> CustomResult<domain::MerchantAccount, StorageError> {let fetch_func = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id).await.map_err(|error| report!(StorageError::from(error)))@@ -228,7 +227,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {merchant_account: domain::MerchantAccountUpdate,merchant_key_store: &MerchantKeyStore,) -> CustomResult<domain::MerchantAccount, StorageError> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let updated_merchant_account = Conversion::convert(this).await@@ -259,7 +258,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {merchant_account: domain::MerchantAccountUpdate,merchant_key_store: &MerchantKeyStore,) -> CustomResult<domain::MerchantAccount, StorageError> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let updated_merchant_account = storage::MerchantAccount::update_with_specific_fields(&conn,merchant_id,@@ -289,7 +288,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {publishable_key: &str,) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> {let fetch_by_pub_key_func = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::MerchantAccount::find_by_publishable_key(&conn, publishable_key).await@@ -337,7 +336,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {organization_id: &common_utils::id_type::OrganizationId,) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {use futures::future::try_join_all;- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;let encrypted_merchant_accounts =storage::MerchantAccount::list_by_organization_id(&conn, organization_id)@@ -380,7 +379,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {&self,merchant_id: &common_utils::id_type::MerchantId,) -> CustomResult<bool, StorageError> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let is_deleted_func = || async {storage::MerchantAccount::delete_by_merchant_id(&conn, merchant_id)@@ -416,7 +415,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {&self,merchant_ids: Vec<common_utils::id_type::MerchantId>,) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;let encrypted_merchant_accounts =storage::MerchantAccount::list_multiple_merchant_accounts(&conn, merchant_ids)@@ -479,7 +478,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {)>,StorageError,> {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;let encrypted_merchant_accounts =storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset).await@@ -500,7 +499,7 @@ impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {&self,merchant_account: domain::MerchantAccountUpdate,) -> CustomResult<usize, StorageError> {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let db_func = || async {storage::MerchantAccount::update_all_merchant_accounts(diff --git a/crates/storage_impl/src/merchant_connector_account.rs b/crates/storage_impl/src/merchant_connector_account.rsindex 081f144b33..2a9879ed73 100644--- a/crates/storage_impl/src/merchant_connector_account.rs+++ b/crates/storage_impl/src/merchant_connector_account.rs@@ -11,9 +11,7 @@ use router_env::instrument;use crate::redis::cache;use crate::{behaviour::{Conversion, ForeignFrom, ReverseConversion},- kv_router_store,- utils::{pg_accounts_connection_read, pg_accounts_connection_write},- CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,+ kv_router_store, CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,};/// Cache keys and invalidation for the merchant connector account list caches.@@ -84,7 +82,7 @@ async fn list_all_by_merchant_id<T: DatabaseStore>(merchant_id: &common_utils::id_type::MerchantId,) -> CustomResult<Vec<storage::MerchantConnectorAccount>, StorageError> {let find_call = || async {- let conn = pg_accounts_connection_read(store).await?;+ let conn = store.pg_accounts_connection_read().await?;storage::MerchantConnectorAccount::list_by_merchant_id(&conn, merchant_id).await.map_err(|error| report!(StorageError::from(error)))@@ -118,7 +116,7 @@ async fn list_all_by_merchant_id_profile_id<T: DatabaseStore>(profile_id: &common_utils::id_type::ProfileId,) -> CustomResult<Vec<storage::MerchantConnectorAccount>, StorageError> {let find_call = || async {- let conn = pg_accounts_connection_read(store).await?;+ let conn = store.pg_accounts_connection_read().await?;storage::MerchantConnectorAccount::list_by_merchant_id_profile_id(&conn,merchant_id,@@ -426,7 +424,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {key_store: &MerchantKeyStore,) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {let find_call = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::MerchantConnectorAccount::find_by_merchant_id_connector(&conn,merchant_id,@@ -482,7 +480,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {key_store: &MerchantKeyStore,) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {let find_call = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::MerchantConnectorAccount::find_by_profile_id_connector_name(&conn,profile_id,@@ -555,7 +553,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {key_store: &MerchantKeyStore,) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {let find_call = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id(&conn,merchant_id,@@ -611,7 +609,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {key_store: &MerchantKeyStore,) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {let find_call = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;storage::MerchantConnectorAccount::find_by_id(&conn, id).await.map_err(|error| report!(Self::Error::from(error)))@@ -661,7 +659,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {let _profile_id = t.profile_id.clone();let insert_call = || async {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;t.construct_new().await.change_context(Self::Error::EncryptionError)?@@ -829,7 +827,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {storage::MerchantConnectorAccountUpdateInternal,)>,) -> CustomResult<(), Self::Error> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;async fn update_call(connection: &diesel_models::DatabaseConnectionWithContext<'_>,@@ -951,7 +949,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {let _merchant_connector_id = this.merchant_connector_id.clone();let update_call = || async {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;Box::pin(Conversion::convert(this).await@@ -1036,7 +1034,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {let _merchant_connector_id = this.get_id().clone();let update_call = || async {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;Box::pin(Conversion::convert(this).await@@ -1108,7 +1106,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {merchant_id: &common_utils::id_type::MerchantId,merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,) -> CustomResult<bool, Self::Error> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let delete_call = || async {storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id(&conn,@@ -1189,7 +1187,7 @@ impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {&self,id: &common_utils::id_type::MerchantConnectorAccountId,) -> CustomResult<bool, Self::Error> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let delete_call = || async {storage::MerchantConnectorAccount::delete_by_id(&conn, id).awaitdiff --git a/crates/storage_impl/src/merchant_key_store.rs b/crates/storage_impl/src/merchant_key_store.rsindex 4d3d0dcf59..2f28a57d70 100644--- a/crates/storage_impl/src/merchant_key_store.rs+++ b/crates/storage_impl/src/merchant_key_store.rs@@ -12,11 +12,7 @@ use crate::redis::{cache,cache::{CacheId, CacheKind},};-use crate::{- kv_router_store,- utils::{pg_accounts_connection_read, pg_accounts_connection_write},- CustomResult, DatabaseStore, MockDb, RouterStore, StorageError,-};+use crate::{kv_router_store, CustomResult, DatabaseStore, MockDb, RouterStore, StorageError};#[async_trait::async_trait]impl<T: DatabaseStore> MerchantKeyStoreInterface for kv_router_store::KVRouterStore<T> {@@ -84,7 +80,7 @@ impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> {merchant_key_store: domain::MerchantKeyStore,key: &Secret<Vec<u8>>,) -> CustomResult<domain::MerchantKeyStore, Self::Error> {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;let merchant_id = merchant_key_store.merchant_id.clone();merchant_key_store.construct_new()@@ -110,7 +106,7 @@ impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> {key: &Secret<Vec<u8>>,) -> CustomResult<domain::MerchantKeyStore, Self::Error> {let fetch_func = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;diesel_models::merchant_key_store::MerchantKeyStore::find_by_merchant_id(&conn,@@ -155,7 +151,7 @@ impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> {merchant_id: &common_utils::id_type::MerchantId,) -> CustomResult<bool, Self::Error> {let delete_func = || async {- let conn = pg_accounts_connection_write(self).await?;+ let conn = self.pg_accounts_connection_write().await?;diesel_models::merchant_key_store::MerchantKeyStore::delete_by_merchant_id(&conn,merchant_id,@@ -190,7 +186,7 @@ impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> {key: &Secret<Vec<u8>>,) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {let fetch_func = || async {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;diesel_models::merchant_key_store::MerchantKeyStore::list_multiple_key_stores(&conn,@@ -221,7 +217,7 @@ impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> {from: u32,to: u32,) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {- let conn = pg_accounts_connection_read(self).await?;+ let conn = self.pg_accounts_connection_read().await?;let stores = diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores(&conn, from, to,)diff --git a/crates/storage_impl/src/tokenization.rs b/crates/storage_impl/src/tokenization.rsindex 774184da28..de37ad6c9e 100644--- a/crates/storage_impl/src/tokenization.rs+++ b/crates/storage_impl/src/tokenization.rs@@ -16,8 +16,10 @@ use crate::{connection, errors};use crate::{kv_router_store::KVRouterStore, DatabaseStore, RouterStore};#[cfg(not(all(feature = "v2", feature = "tokenization_v2")))]+#[router_derive::track_async_interface]pub trait TokenizationInterface {}+#[router_derive::track_async_interface]#[async_trait::async_trait]#[cfg(all(feature = "v2", feature = "tokenization_v2"))]pub trait TokenizationInterface {@@ -126,9 +128,12 @@ impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> {merchant_key_store: &MerchantKeyStore,) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>{- self.router_store- .insert_tokenization(tokenization, merchant_key_store)- .await+ TokenizationInterface::insert_tokenization(+ &self.router_store,+ tokenization,+ merchant_key_store,+ )+ .await}async fn get_entity_id_vault_id_by_token_id(@@ -137,9 +142,12 @@ impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> {merchant_key_store: &MerchantKeyStore,) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>{- self.router_store- .get_entity_id_vault_id_by_token_id(token, merchant_key_store)- .await+ TokenizationInterface::get_entity_id_vault_id_by_token_id(+ &self.router_store,+ token,+ merchant_key_store,+ )+ .await}async fn update_tokenization_record(@@ -149,13 +157,13 @@ impl<T: DatabaseStore> TokenizationInterface for KVRouterStore<T> {merchant_key_store: &MerchantKeyStore,) -> CustomResult<hyperswitch_domain_models::tokenization::Tokenization, errors::StorageError>{- self.router_store- .update_tokenization_record(- tokenization_record,- tokenization_update,- merchant_key_store,- )- .await+ TokenizationInterface::update_tokenization_record(+ &self.router_store,+ tokenization_record,+ tokenization_update,+ merchant_key_store,+ )+ .await}}diff --git a/crates/storage_impl/src/utils.rs b/crates/storage_impl/src/utils.rsindex 3a584de97f..8bf07093fc 100644--- a/crates/storage_impl/src/utils.rs+++ b/crates/storage_impl/src/utils.rs@@ -228,79 +228,6 @@ pub async fn pg_connection_write<'a, T: DatabaseStore + RequestContext>())}-pub async fn pg_accounts_connection_read<'a, T: DatabaseStore + RequestContext>(- store: &'a T,-) -> error_stack::Result<DatabaseConnectionWithContext<'a>, StorageError> {- // If only OLAP is enabled, get the replica pool.- #[cfg(all(feature = "olap", not(feature = "oltp")))]- let (pool, db_pool_label) = (- store.get_accounts_replica_pool(),- pool_metrics::DbPool::AccountsReplica,- );-- // If either one of these is true, get the master pool:- // 1. Only OLTP is enabled.- // 2. Both OLAP and OLTP are enabled.- // 3. Both OLAP and OLTP are disabled.- #[cfg(any(- all(not(feature = "olap"), feature = "oltp"),- all(feature = "olap", feature = "oltp"),- all(not(feature = "olap"), not(feature = "oltp"))- ))]- let (pool, db_pool_label) = (- store.get_accounts_master_pool(),- pool_metrics::DbPool::AccountsMaster,- );- let tenant_id = pool.tenant_id.get_string_repr();-- #[cfg_attr(not(feature = "deja"), allow(unused_mut))]- let mut connection = metrics::record_db_connection_acquire_duration(- pool.pg_pool.get(),- db_pool_label,- tenant_id,- )- .await- .change_context(StorageError::DatabaseConnectionError)?;-- #[cfg(feature = "deja")]- deja_route_replay_schema(&mut connection, store).await;-- Ok(DatabaseConnectionWithContext::new(- connection,- store.request_id().map(str::to_owned),- pool.event_emitter.clone(),- store.read_ledger().cloned(),- ))-}--pub async fn pg_accounts_connection_write<'a, T: DatabaseStore + RequestContext>(- store: &'a T,-) -> error_stack::Result<DatabaseConnectionWithContext<'a>, StorageError> {- // Since all writes should happen to master DB only choose master DB.- let pool = store.get_accounts_master_pool();-- let tenant_id = pool.tenant_id.get_string_repr();-- #[cfg_attr(not(feature = "deja"), allow(unused_mut))]- let mut connection = metrics::record_db_connection_acquire_duration(- pool.pg_pool.get(),- pool_metrics::DbPool::AccountsMaster,- tenant_id,- )- .await- .change_context(StorageError::DatabaseConnectionError)?;-- #[cfg(feature = "deja")]- deja_route_replay_schema(&mut connection, store).await;-- Ok(DatabaseConnectionWithContext::new(- connection,- store.request_id().map(str::to_owned),- pool.event_emitter.clone(),- store.read_ledger().cloned(),- ))-}-pub async fn try_redis_get_else_try_database_get<F, RFut, DFut, T>(redis_fut: RFut,database_call_closure: F,