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
feat(router): report session duplicate reads with accounts query origins (#15128)
Hrithikesh3560148f990e
diff --git a/crates/common_utils/src/read_ledger.rs b/crates/common_utils/src/read_ledger.rsindex e8fcb7ff81..21c12e6d3f 100644--- a/crates/common_utils/src/read_ledger.rs+++ b/crates/common_utils/src/read_ledger.rs@@ -4,7 +4,8 @@//! statement including bind values, so different parameters stay distinct.use std::{- collections::HashSet,+ collections::HashMap,+ panic::Location,sync::{Arc, Mutex},};@@ -37,7 +38,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<HashSet<String>>>,+ reads: Arc<Mutex<HashMap<String, Vec<Option<Location<'static>>>>>>,}impl ReadLedger {@@ -46,7 +47,7 @@ impl ReadLedger {Self {flow,store: ReadStore::Main,- reads: Arc::new(Mutex::new(HashSet::new())),+ reads: Arc::new(Mutex::new(HashMap::new())),}}@@ -68,20 +69,37 @@ impl ReadLedger {self.store}- /// Record a read, returning whether the session already read the same SQL- /// with the same bind values. Only the first read allocates a stored key.- pub fn record_read(&self, statement: &str) -> bool {+ /// 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.+ pub fn record_read(&self, statement: &str, location: Option<Location<'static>>) -> bool {let mut reads = self.reads.lock().unwrap_or_else(std::sync::PoisonError::into_inner);- if reads.contains(statement) {+ if let Some(locations) = reads.get_mut(statement) {+ locations.push(location);true} else {- reads.insert(statement.to_owned());+ reads.insert(statement.to_owned(), vec![location]);false}}++ /// Return statements read more than once, with locations in recording order.+ pub fn duplicate_reads(&self) -> Vec<(String, Vec<Option<Location<'static>>>)> {+ let reads = self+ .reads+ .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+ }}#[cfg(test)]@@ -91,30 +109,56 @@ mod tests {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!(!ledger.record_read(PI));+ assert!(!record_read(&ledger, PI));for _ in 0..20 {- assert!(ledger.record_read(PI));+ 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!(!ledger.record_read(PI));- assert!(!ledger.record_read(OTHER));- assert!(ledger.record_read(OTHER));- assert!(ledger.record_read(PI));+ 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!(!first.record_read(PI));- assert!(!second.record_read(PI));+ assert!(!record_read(&first, PI));+ assert!(!record_read(&second, PI));}#[test]@@ -130,30 +174,30 @@ mod tests {assert_eq!(ledger.flow(), "PaymentsConfirm");}- assert!(!main.record_read(PI));- assert!(accounts.record_read(PI));- assert!(global.record_read(PI));- assert!(!accounts.record_read(OTHER));- assert!(main.record_read(OTHER));+ 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!(!ledger.record_read("SELECT 1908"));- assert!(!ledger.record_read("SELECT 3600"));- assert!(ledger.record_read("SELECT 1908"));- assert!(ledger.record_read("SELECT 3600"));+ 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!(!ledger.record_read(&format!("SELECT {index}")));+ assert!(!record_read(&ledger, &format!("SELECT {index}")));}- assert!(ledger.record_read("SELECT 0"));- assert!(ledger.record_read("SELECT 4999"));+ assert!(record_read(&ledger, "SELECT 0"));+ assert!(record_read(&ledger, "SELECT 4999"));}#[test]@@ -166,7 +210,7 @@ mod tests {let barrier = Arc::clone(&barrier);std::thread::spawn(move || {barrier.wait();- ledger.record_read(PI)+ record_read(&ledger, PI)})}).collect::<Vec<_>>();diff --git a/crates/diesel_models/src/query/generics.rs b/crates/diesel_models/src/query/generics.rsindex af6555c295..6f48d89e06 100644--- a/crates/diesel_models/src/query/generics.rs+++ b/crates/diesel_models/src/query/generics.rs@@ -198,7 +198,7 @@ impl DatabaseConnectionWithContext<'_> {.await}- /// Log statements and track duplicate reads when called; measure execution when polled.+ /// Track duplicate reads when called; measure execution when polled./// Emit a database-call event only when a request ID is present.////// The returned future does not borrow the statement or ledger. Its `Send`@@ -223,7 +223,8 @@ impl DatabaseConnectionWithContext<'_> {logger::debug!(query = %statement);if let (Some(ledger), true) = (self.read_ledger(), operation.is_read()) {- if ledger.record_read(statement) {+ let location = router_env::call_origin::current_origin().copied();+ if ledger.record_read(statement, location) {crate::metrics::DUPLICATE_DB_READ_COUNT.add(1,router_env::metric_attributes!(diff --git a/crates/router/src/core/admin.rs b/crates/router/src/core/admin.rsindex 52ff35225a..d43b7a0534 100644--- a/crates/router/src/core/admin.rs+++ b/crates/router/src/core/admin.rs@@ -123,8 +123,7 @@ pub async fn create_organization() -> RouterResponse<api::OrganizationResponse> {let db_organization = ForeignFrom::foreign_from(req);state- .accounts_store- .insert_organization(db_organization)+ .track_accounts_query(|db| db.insert_organization(db_organization)).await.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {message: "Organization with the given organization_name already exists".to_string(),@@ -146,8 +145,9 @@ pub async fn update_organization(metadata: req.metadata,};state- .accounts_store- .update_organization_by_org_id(&org_id.organization_id, organization_update)+ .track_accounts_query(|db| {+ db.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,16 +167,24 @@ pub async fn get_organization() -> RouterResponse<api::OrganizationResponse> {#[cfg(all(feature = "v1", feature = "olap"))]{- CreateOrValidateOrganization::new(Some(org_id.organization_id), None)- .create_or_validate(state.accounts_store.as_ref())+ state+ .track_accounts_query(|db| async move {+ CreateOrValidateOrganization::new(Some(org_id.organization_id), None)+ .create_or_validate(db)+ .await+ }).await.map(ForeignFrom::foreign_from).map(service_api::ApplicationResponse::Json)}#[cfg(all(feature = "v2", feature = "olap"))]{- CreateOrValidateOrganization::new(org_id.organization_id)- .create_or_validate(state.accounts_store.as_ref())+ state+ .track_accounts_query(|db| async move {+ CreateOrValidateOrganization::new(org_id.organization_id)+ .create_or_validate(db)+ .await+ }).await.map(ForeignFrom::foreign_from).map(service_api::ApplicationResponse::Json)@@ -230,8 +238,7 @@ pub async fn convert_organization_to_platform_organization(})?;let organization = state- .accounts_store- .find_organization_by_org_id(&org_id.organization_id)+ .track_accounts_query(|db| db.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(),@@ -256,11 +263,12 @@ pub async fn convert_organization_to_platform_organization(})?;state- .accounts_store- .update_organization_by_org_id(- &org_id.organization_id,- diesel_models::organization::OrganizationUpdate::ConvertToPlatform,- )+ .track_accounts_query(|db| {+ db.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")?;@@ -297,13 +305,14 @@ pub async fn convert_organization_to_platform_organization(.await?;let updated_organization = state- .accounts_store- .update_organization_by_org_id(- &org_id.organization_id,- diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {- platform_merchant_id: platform_merchant_id.clone(),- },- )+ .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(),+ },+ )+ }).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to update organization type to Platform")?;@@ -388,13 +397,14 @@ pub async fn create_merchant_account(if merchant_account.is_platform_account() {state- .accounts_store- .update_organization_by_org_id(- &merchant_account.organization_id,- diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {- platform_merchant_id: merchant_id.clone(),- },- )+ .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(),+ },+ )+ }).await.change_context(errors::ApiErrorResponse::InternalServerError).attach_printable("Failed to update organization with platform_merchant_id")?;@@ -439,7 +449,6 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {identifier: &id_type::MerchantId,org_data_from_auth: Option<authentication::AuthenticationDataWithOrg>,) -> RouterResult<domain::MerchantAccount> {- let db = &*state.accounts_store;let publishable_key = create_merchant_publishable_key();let primary_business_details = self.get_primary_details_as_value().change_context(@@ -518,8 +527,13 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {(req_org_id, _) => req_org_id.clone(),};- let organization = CreateOrValidateOrganization::new(org_id, self.merchant_account_type)- .create_or_validate(db)+ 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+ }).await?;let merchant_account_type = match organization.get_organization_type() {@@ -896,7 +910,6 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {_org_data: Option<authentication::AuthenticationDataWithOrg>,) -> RouterResult<domain::MerchantAccount> {let publishable_key = create_merchant_publishable_key();- let db = &*state.accounts_store;let metadata = self.get_metadata_as_secret().change_context(errors::ApiErrorResponse::InvalidDataValue {@@ -910,8 +923,13 @@ impl MerchantAccountCreateBridge for api::MerchantAccountCreate {},)?;- let organization = CreateOrValidateOrganization::new(self.organization_id.clone())- .create_or_validate(db)+ 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+ }).await?;// V2 currently supports creation of Standard merchant accounts only, irrespective of organization typediff --git a/crates/router/src/core/disputes.rs b/crates/router/src/core/disputes.rsindex a18a547466..dd79f80b3a 100644--- a/crates/router/src/core/disputes.rs+++ b/crates/router/src/core/disputes.rs@@ -1263,8 +1263,9 @@ pub async fn schedule_dispute_sync_task(.attach_printable("Error while fetching the merchant account for processor")?;let organization = state- .accounts_store- .find_organization_by_org_id(processor_account.get_org_id())+ .track_accounts_query(|db| {+ db.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/user.rs b/crates/router/src/core/user.rsindex 21cad82509..b2554b8b5e 100644--- a/crates/router/src/core/user.rs+++ b/crates/router/src/core/user.rs@@ -1804,14 +1804,16 @@ pub async fn create_platform_account(.create_new_merchant_and_insert_in_db(state.to_owned()).await?;+ let organization_id = organization.get_organization_id();state- .accounts_store- .update_organization_by_org_id(- &organization.get_organization_id(),- diesel_models::organization::OrganizationUpdate::UpdatePlatformMerchant {- platform_merchant_id: merchant_account.get_id().clone(),- },- )+ .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(),+ },+ )+ }).await.change_context(UserErrors::InternalServerError)?;@@ -1857,8 +1859,7 @@ pub async fn create_org_merchant_for_user() -> UserResponse<()> {let db_organization = ForeignFrom::foreign_from(req.clone());let org: diesel_models::organization::Organization = state- .accounts_store- .insert_organization(db_organization)+ .track_accounts_query(|db| db.insert_organization(db_organization)).await.change_context(UserErrors::InternalServerError)?;let default_product_type = consts::user::DEFAULT_PRODUCT_TYPE;@@ -1961,8 +1962,7 @@ pub async fn list_user_roles_details(.collect::<HashSet<_>>();let org_name = state- .accounts_store- .find_organization_by_org_id(&user_from_token.org_id)+ .track_accounts_query(|db| db.find_organization_by_org_id(&user_from_token.org_id)).await.change_context(UserErrors::InternalServerError).attach_printable("Org id not found")?@@ -3249,7 +3249,7 @@ pub async fn list_orgs_for_user(let resp = futures::future::try_join_all(orgs.iter()- .map(|org_id| state.accounts_store.find_organization_by_org_id(org_id)),+ .map(|org_id| state.track_accounts_query(|db| db.find_organization_by_org_id(org_id))),).await.change_context(UserErrors::InternalServerError)?diff --git a/crates/router/src/core/user_role.rs b/crates/router/src/core/user_role.rsindex fb7c406133..f09a3a8a16 100644--- a/crates/router/src/core/user_role.rs+++ b/crates/router/src/core/user_role.rs@@ -1067,8 +1067,7 @@ 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- .accounts_store- .find_organization_by_org_id(&org_id)+ .track_accounts_query(|db| db.find_organization_by_org_id(&org_id)).await.change_context(UserErrors::InternalServerError)?.get_organization_name()diff --git a/crates/router/src/db.rs b/crates/router/src/db.rsindex c3834c95d4..b97f3162f5 100644--- a/crates/router/src/db.rs+++ b/crates/router/src/db.rs@@ -379,6 +379,10 @@ pub trait RequestIdStore {_read_ledger: std::sync::Arc<common_utils::read_ledger::ReadLedger>,) {}++ fn get_read_ledger(&self) -> Option<std::sync::Arc<common_utils::read_ledger::ReadLedger>> {+ None+ }}impl RequestIdStore for MockDb {}@@ -417,6 +421,17 @@ impl RequestIdStore for Store {self.read_ledger = Some(read_ledger);}}++ fn get_read_ledger(&self) -> Option<std::sync::Arc<common_utils::read_ledger::ReadLedger>> {+ #[cfg(feature = "kv_store")]+ {+ self.router_store.read_ledger.clone()+ }+ #[cfg(not(feature = "kv_store"))]+ {+ self.read_ledger.clone()+ }+ }}pub async fn get_and_deserialize_key<T>(@@ -450,6 +465,10 @@ impl RequestIdStore for KafkaStore {) {self.diesel_store.attach_read_ledger(read_ledger)}++ fn get_read_ledger(&self) -> Option<std::sync::Arc<common_utils::read_ledger::ReadLedger>> {+ self.diesel_store.get_read_ledger()+ }}#[async_trait::async_trait]diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex f16cb1b87e..09d9d60bf1 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1,4 +1,4 @@-use std::{collections::HashMap, sync::Arc};+use std::{collections::HashMap, future::Future, panic::Location, 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>,- pub accounts_store: Box<dyn AccountsStorageInterface>,+ accounts_store: Box<dyn AccountsStorageInterface>,pub conf: Arc<settings::Settings<RawSecret>>,pub api_client: Box<dyn crate::services::ApiClient>,pub event_handler: EventsHandler,@@ -184,6 +184,22 @@ impl scheduler::SchedulerSessionState for SessionState {}}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+ })+ }/// Resolve the runtime callback policy once for this request and its clones.pub async fn payment_callback_config(&self) -> RouterResult<&PaymentCallbackConfig> {self.payment_callback_config@@ -251,6 +267,7 @@ pub trait SessionStateInfo {fn get_request_id(&self) -> Option<String>;fn add_request_id(&mut self, request_id: RequestId);fn start_read_ledger(&mut self, flow: String);+ fn get_read_ledger(&self) -> Option<Arc<common_utils::read_ledger::ReadLedger>>;#[cfg(feature = "partial-auth")]fn get_detached_auth(&self) -> RouterResult<(Blake3, &[u8])>;fn session_state(&self) -> SessionState;@@ -274,6 +291,10 @@ impl SessionStateInfo for SessionState {self.store.attach_read_ledger(read_ledger);}+ fn get_read_ledger(&self) -> Option<Arc<common_utils::read_ledger::ReadLedger>> {+ self.store.get_read_ledger()+ }+fn store(&self) -> Box<dyn StorageInterface> {self.store.to_owned()}diff --git a/crates/router/src/services/api.rs b/crates/router/src/services/api.rsindex 5b2d031f77..6ef12f58b1 100644--- a/crates/router/src/services/api.rs+++ b/crates/router/src/services/api.rs@@ -397,6 +397,17 @@ 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"+ );+ }+ }+output}diff --git a/crates/router/src/services/authentication.rs b/crates/router/src/services/authentication.rsindex 6761a3eb7b..c5597ffc7f 100644--- a/crates/router/src/services/authentication.rs+++ b/crates/router/src/services/authentication.rs@@ -6830,10 +6830,9 @@ pub(crate) async fn get_platform_account_and_key_store<A>(whereA: SessionStateInfo + Sync,{- let organization = state- .session_state()- .accounts_store- .find_organization_by_org_id(merchant_account.get_org_id())+ 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())).await.change_context(errors::ApiErrorResponse::InvalidPlatformOperation).attach_printable("Failed to fetch organization for connected merchant")?;diff --git a/crates/router/src/types/domain/user.rs b/crates/router/src/types/domain/user.rsindex 24fcb411ec..42a9079168 100644--- a/crates/router/src/types/domain/user.rs+++ b/crates/router/src/types/domain/user.rs@@ -250,8 +250,7 @@ pub struct NewUserOrganization(diesel_org::OrganizationNew);impl NewUserOrganization {pub async fn insert_org_in_db(self, state: SessionState) -> UserResult<Organization> {state- .accounts_store- .insert_organization(self.0)+ .track_accounts_query(|db| db.insert_organization(self.0)).await.map_err(|e| {if e.current_context().is_db_unique_violation() {@@ -929,12 +928,11 @@ impl NewUser {platform_merchant_id: merchant_id.clone(),};+ let organization_id = self.new_merchant.new_organization.get_organization_id();state- .accounts_store- .update_organization_by_org_id(- &self.new_merchant.new_organization.get_organization_id(),- org_update,- )+ .track_accounts_query(|db| {+ db.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/utils/user/theme.rs b/crates/router/src/utils/user/theme.rsindex 50f182aefd..1bd43b0ca5 100644--- a/crates/router/src/utils/user/theme.rs+++ b/crates/router/src/utils/user/theme.rs@@ -152,8 +152,7 @@ fn validate_tenant(state: &SessionState, tenant_id: &id_type::TenantId) -> UserRasync fn validate_org(state: &SessionState, org_id: &id_type::OrganizationId) -> UserResult<()> {state- .accounts_store- .find_organization_by_org_id(org_id)+ .track_accounts_query(|db| db.find_organization_by_org_id(org_id)).await.to_not_found_response(UserErrors::InvalidThemeLineage("org_id".to_string())).map(|_| ())diff --git a/crates/router/src/utils/user_role.rs b/crates/router/src/utils/user_role.rsindex 37b443b5bc..735548059f 100644--- a/crates/router/src/utils/user_role.rs+++ b/crates/router/src/utils/user_role.rs@@ -640,8 +640,7 @@ pub async fn send_role_deletion_email_using_db(.unwrap_or(state.conf.theme.email_config.clone());let org = state- .accounts_store- .find_organization_by_org_id(&user_from_token.org_id)+ .track_accounts_query(|db| db.find_organization_by_org_id(&user_from_token.org_id)).await.change_context(UserErrors::InternalServerError)?;diff --git a/crates/router_env/Cargo.toml b/crates/router_env/Cargo.tomlindex 4208a53fbf..e16310d997 100644--- a/crates/router_env/Cargo.toml+++ b/crates/router_env/Cargo.toml@@ -29,7 +29,7 @@ serde_json = "1.0.140"serde_path_to_error = "0.1.17"strum = { version = "0.26.3", features = ["derive"] }time = { version = "0.3.41", default-features = false, features = ["formatting"] }-tokio = { version = "1.48.0" }+tokio = { version = "1.48.0", features = ["rt"] }tracing = { workspace = true }actix-web = { version = "4.11.0", optional = true }tracing-actix-web = { version = "0.7.18", features = ["opentelemetry_0_27", "uuid_v7"], optional = true }diff --git a/crates/router_env/src/call_origin.rs b/crates/router_env/src/call_origin.rsnew file mode 100644index 0000000000..cf6d41c8ce--- /dev/null+++ b/crates/router_env/src/call_origin.rs@@ -0,0 +1,40 @@+//! Carries an operation's call location across async boundaries.++use std::{future::Future, panic::Location};++tokio::task_local! {+ static ORIGIN: &'static Location<'static>;+}++/// Run a future with a caller location in the current task's context.+pub fn with_origin<F: Future>(+ origin: &'static Location<'static>,+ future: F,+) -> impl Future<Output = F::Output> {+ ORIGIN.scope(origin, future)+}++/// Return the current caller location, if one was scoped.+pub fn current_origin() -> Option<&'static Location<'static>> {+ ORIGIN.try_with(|origin| *origin).ok()+}++#[cfg(test)]+mod tests {+ use super::*;++ #[tokio::test]+ async fn origin_survives_await_and_is_removed_after_scope() {+ assert!(current_origin().is_none());++ let expected = line!() + 1;+ let observed = with_origin(Location::caller(), async {+ tokio::task::yield_now().await;+ current_origin().map(Location::line)+ })+ .await;++ assert_eq!(observed, Some(expected));+ assert!(current_origin().is_none());+ }+}diff --git a/crates/router_env/src/lib.rs b/crates/router_env/src/lib.rsindex 54a2529357..68165fff05 100644--- a/crates/router_env/src/lib.rs+++ b/crates/router_env/src/lib.rs@@ -4,6 +4,8 @@#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]+/// Origin of an operation within an async task.+pub mod call_origin;/// Utilities to identify members of the current cargo workspace.pub mod cargo_workspace;pub mod env;