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(migration): add global ID migration for customers (#12654)
Kashif6607fe50b107
diff --git a/crates/api_models/src/customers.rs b/crates/api_models/src/customers.rsindex 59b65e0538..c2051b3eab 100644--- a/crates/api_models/src/customers.rs+++ b/crates/api_models/src/customers.rs@@ -13,6 +13,9 @@ use utoipa::ToSchema;use crate::payments;+#[cfg(feature = "v2")]+pub mod migrate;+/// The customer details#[cfg(feature = "v1")]#[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema, SmithyModel)]diff --git a/crates/api_models/src/customers/migrate.rs b/crates/api_models/src/customers/migrate.rsnew file mode 100644index 0000000000..63cb205d1d--- /dev/null+++ b/crates/api_models/src/customers/migrate.rs@@ -0,0 +1,43 @@+use common_utils::{events::ApiEventMetric, id_type};+use serde::Serialize;+use utoipa::ToSchema;++#[derive(Debug, Clone, Serialize, ToSchema)]+#[serde(rename_all = "snake_case")]+pub enum CustomerGlobalIdMigrationStatus {+ UpdatedNullId,+ UpdatedNonGlobalId,+ AlreadyGlobalId,+ SkippedNonV1,+ NotFound,+ InvalidCsvRow,+ UpdateFailed,+}++#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct CustomerGlobalIdMigrationRowResult {+ pub row_number: usize,+ #[schema(value_type = Option<String>)]+ pub merchant_id: Option<id_type::MerchantId>,+ #[schema(value_type = Option<String>)]+ pub customer_id: Option<id_type::CustomerId>,+ pub status: CustomerGlobalIdMigrationStatus,+ pub old_id: Option<String>,+ pub new_id: Option<String>,+ pub message: String,+}++#[derive(Debug, Clone, Serialize, ToSchema)]+pub struct CustomerGlobalIdMigrationResponse {+ pub total_rows: usize,+ pub updated_count: usize,+ pub skipped_count: usize,+ pub failed_count: usize,+ pub results: Vec<CustomerGlobalIdMigrationRowResult>,+}++impl ApiEventMetric for CustomerGlobalIdMigrationResponse {+ fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {+ Some(common_utils::events::ApiEventsType::Miscellaneous)+ }+}diff --git a/crates/diesel_models/src/customers.rs b/crates/diesel_models/src/customers.rsindex ea8a676d82..df695a4255 100644--- a/crates/diesel_models/src/customers.rs+++ b/crates/diesel_models/src/customers.rs@@ -201,6 +201,15 @@ pub struct Customer {pub customer_id: Option<common_utils::id_type::GlobalCustomerId>,}+#[cfg(feature = "v2")]+#[derive(Clone, Debug, diesel::Queryable, serde::Serialize, serde::Deserialize)]+pub struct CustomerGlobalIdMigrationRow {+ pub merchant_id: common_utils::id_type::MerchantId,+ pub customer_id: Option<String>,+ pub id: Option<String>,+ pub version: ApiVersion,+}+#[cfg(feature = "v1")]#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay, serde::Deserialize, serde::Serialize,diff --git a/crates/diesel_models/src/query/customers.rs b/crates/diesel_models/src/query/customers.rsindex dffcfb4383..ca4f70c4d3 100644--- a/crates/diesel_models/src/query/customers.rs+++ b/crates/diesel_models/src/query/customers.rs@@ -1,7 +1,15 @@+#[cfg(feature = "v2")]+use async_bb8_diesel::AsyncRunQueryDsl;use common_utils::id_type;use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};+#[cfg(feature = "v2")]+use diesel::{NullableExpressionMethods, QueryDsl};+#[cfg(feature = "v2")]+use error_stack::{report, ResultExt};use super::generics;+#[cfg(feature = "v2")]+use crate::customers::CustomerGlobalIdMigrationRow;#[cfg(feature = "v1")]use crate::schema::customers::dsl;#[cfg(feature = "v2")]@@ -32,6 +40,73 @@ pub struct CustomerListConstraints {}impl Customer {+ #[cfg(feature = "v2")]+ pub async fn find_by_merchant_id_customer_id_for_global_id_migration(+ conn: &PgPooledConn,+ merchant_id: &id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ ) -> StorageResult<CustomerGlobalIdMigrationRow> {+ let customer_id = Some(customer_id.get_string_repr().to_owned());++ let query = dsl::customers+ .filter(dsl::merchant_id.eq(merchant_id.to_owned()))+ .filter(dsl::customer_id.eq(customer_id))+ .select((+ dsl::merchant_id,+ dsl::customer_id,+ dsl::id.nullable(),+ dsl::version,+ ));++ match query+ .first_async::<CustomerGlobalIdMigrationRow>(conn)+ .await+ {+ Ok(row) => Ok(row),+ Err(diesel::result::Error::NotFound) => Err(report!(errors::DatabaseError::NotFound))+ .attach_printable("No customer found for global id migration"),+ Err(error) => Err(error)+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error while finding customer for global id migration"),+ }+ }++ #[cfg(feature = "v2")]+ pub async fn update_global_id_for_migration(+ conn: &PgPooledConn,+ merchant_id: &id_type::MerchantId,+ customer_id: &id_type::CustomerId,+ new_id: id_type::GlobalCustomerId,+ ) -> StorageResult<CustomerGlobalIdMigrationRow> {+ let customer_id = Some(customer_id.get_string_repr().to_owned());++ let query = diesel::update(+ dsl::customers+ .filter(dsl::merchant_id.eq(merchant_id.to_owned()))+ .filter(dsl::customer_id.eq(customer_id))+ .filter(dsl::version.eq(common_enums::ApiVersion::V1)),+ )+ .set(dsl::id.eq(new_id))+ .returning((+ dsl::merchant_id,+ dsl::customer_id,+ dsl::id.nullable(),+ dsl::version,+ ));++ match query+ .get_result_async::<CustomerGlobalIdMigrationRow>(conn)+ .await+ {+ Ok(row) => Ok(row),+ Err(diesel::result::Error::NotFound) => Err(report!(errors::DatabaseError::NotFound))+ .attach_printable("No v1 customer found while updating global id"),+ Err(error) => Err(error)+ .change_context(errors::DatabaseError::Others)+ .attach_printable("Error while updating customer global id"),+ }+ }+#[cfg(feature = "v2")]pub async fn update_by_id(conn: &PgPooledConn,diff --git a/crates/hyperswitch_domain_models/src/customer.rs b/crates/hyperswitch_domain_models/src/customer.rsindex ae0788ddc0..616344e972 100644--- a/crates/hyperswitch_domain_models/src/customer.rs+++ b/crates/hyperswitch_domain_models/src/customer.rs@@ -772,6 +772,21 @@ wherestorage_scheme: MerchantStorageScheme,) -> CustomResult<Option<Customer>, Self::Error>;+ #[cfg(feature = "v2")]+ async fn find_customer_for_global_id_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ ) -> CustomResult<storage_types::CustomerGlobalIdMigrationRow, Self::Error>;++ #[cfg(feature = "v2")]+ async fn update_customer_global_id_for_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ new_id: id_type::GlobalCustomerId,+ ) -> CustomResult<storage_types::CustomerGlobalIdMigrationRow, Self::Error>;+#[cfg(feature = "v1")]#[allow(clippy::too_many_arguments)]async fn update_customer_by_customer_id_merchant_id(diff --git a/crates/router/src/db/kafka_store.rs b/crates/router/src/db/kafka_store.rsindex e31e0f092f..1d822ab2e7 100644--- a/crates/router/src/db/kafka_store.rs+++ b/crates/router/src/db/kafka_store.rs@@ -428,6 +428,29 @@ impl CustomerInterface for KafkaStore {.await}+ #[cfg(feature = "v2")]+ async fn find_customer_for_global_id_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ ) -> CustomResult<storage::CustomerGlobalIdMigrationRow, errors::StorageError> {+ self.diesel_store+ .find_customer_for_global_id_migration(customer_id, merchant_id)+ .await+ }++ #[cfg(feature = "v2")]+ async fn update_customer_global_id_for_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ new_id: id_type::GlobalCustomerId,+ ) -> CustomResult<storage::CustomerGlobalIdMigrationRow, errors::StorageError> {+ self.diesel_store+ .update_customer_global_id_for_migration(customer_id, merchant_id, new_id)+ .await+ }+#[cfg(feature = "v1")]async fn update_customer_by_customer_id_merchant_id(&self,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex aff6691231..5d566f16b7 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -1420,6 +1420,10 @@ impl Customers {{route = route.service(web::resource("").route(web::post().to(customers::customers_create)))+ .service(+ web::resource("/migrate/global-id")+ .route(web::post().to(customers::migrate::migrate_global_id)),+ ).service(web::resource("/{id}").route(web::put().to(customers::customers_update))diff --git a/crates/router/src/routes/customers.rs b/crates/router/src/routes/customers.rsindex 6dd293c915..ac9d2b027e 100644--- a/crates/router/src/routes/customers.rs+++ b/crates/router/src/routes/customers.rs@@ -2,6 +2,9 @@ use actix_web::{web, HttpRequest, HttpResponse, Responder};use common_utils::id_type;use router_env::{instrument, tracing, Flow};+#[cfg(feature = "v2")]+pub mod migrate;+use super::app::AppState;#[cfg(feature = "v1")]use crate::core::utils as core_utils;diff --git a/crates/router/src/routes/customers/migrate.rs b/crates/router/src/routes/customers/migrate.rsnew file mode 100644index 0000000000..3fe0268a86--- /dev/null+++ b/crates/router/src/routes/customers/migrate.rs@@ -0,0 +1,459 @@+use std::marker::PhantomData;++use actix_multipart::form::{bytes::Bytes as MultipartBytes, MultipartForm};+use actix_web::{web, HttpRequest, HttpResponse};+use api_models::customers::migrate::{+ CustomerGlobalIdMigrationResponse, CustomerGlobalIdMigrationRowResult,+ CustomerGlobalIdMigrationStatus,+};+use common_enums::ApiVersion;+use common_utils::id_type;+use error_stack::{report, ResultExt};+use router_env::{instrument, logger, tracing, Flow};++use crate::{+ core::{api_locking, errors},+ routes::{app::AppState, SessionState},+ services::{api, authentication as auth, ApplicationResponse},+};++pub const MAX_CUSTOMER_GLOBAL_ID_MIGRATION_FILE_SIZE: usize = 1024 * 1024;+pub const MAX_CUSTOMER_GLOBAL_ID_MIGRATION_RECORDS: usize = 500;+pub const MAX_CUSTOMER_GLOBAL_ID_MIGRATION_PARALLELISM: usize = 10;++type MigrationStepResult<T> = Result<T, Box<CustomerGlobalIdMigrationRowResult>>;++#[derive(Debug, MultipartForm)]+pub struct CustomerGlobalIdMigrationForm {+ #[multipart(limit = "1MB")]+ pub file: MultipartBytes,+}++#[instrument(skip_all, fields(flow = ?Flow::CustomersGlobalIdMigration))]+pub async fn migrate_global_id(+ state: web::Data<AppState>,+ req: HttpRequest,+ MultipartForm(form): MultipartForm<CustomerGlobalIdMigrationForm>,+) -> HttpResponse {+ let flow = Flow::CustomersGlobalIdMigration;+ let csv_bytes = form.file.data.to_vec();++ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ (),+ |state, _, _payload, _| {+ let csv_bytes = csv_bytes.clone();+ async move { migrate_customer_global_id(state, &csv_bytes).await }+ },+ &auth::V2AdminApiAuth,+ api_locking::LockAction::NotApplicable,+ ))+ .await+}++async fn migrate_customer_global_id(+ state: SessionState,+ csv_bytes: &[u8],+) -> errors::RouterResponse<CustomerGlobalIdMigrationResponse> {+ let rows = parse_customer_global_id_migration_csv(csv_bytes)?;+ let total_rows = rows.len();+ let mut results = Vec::with_capacity(total_rows);+ let mut rows = rows.into_iter();++ loop {+ let row_chunk = rows+ .by_ref()+ .take(MAX_CUSTOMER_GLOBAL_ID_MIGRATION_PARALLELISM)+ .collect::<Vec<_>>();++ if row_chunk.is_empty() {+ break;+ }++ let chunk_results = futures::future::join_all(row_chunk.into_iter().map(|row| async {+ let result = match row {+ Ok(row) => process_fetched_row(row.fetch(&state).await, &state).await,+ Err(result) => *result,+ };+ log_row_result(&result);+ result+ }))+ .await;++ results.extend(chunk_results);+ }++ let updated_count = results+ .iter()+ .filter(|result| {+ matches!(+ result.status,+ CustomerGlobalIdMigrationStatus::UpdatedNullId+ | CustomerGlobalIdMigrationStatus::UpdatedNonGlobalId+ )+ })+ .count();+ let skipped_count = results+ .iter()+ .filter(|result| {+ matches!(+ result.status,+ CustomerGlobalIdMigrationStatus::AlreadyGlobalId+ | CustomerGlobalIdMigrationStatus::SkippedNonV1+ )+ })+ .count();+ let failed_count = total_rows - updated_count - skipped_count;++ Ok(ApplicationResponse::Json(+ CustomerGlobalIdMigrationResponse {+ total_rows,+ updated_count,+ skipped_count,+ failed_count,+ results,+ },+ ))+}++fn parse_customer_global_id_migration_csv(+ csv_bytes: &[u8],+) -> errors::RouterResult<Vec<MigrationStepResult<MigrationRow<Parsed>>>> {+ if csv_bytes.len() > MAX_CUSTOMER_GLOBAL_ID_MIGRATION_FILE_SIZE {+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "CSV file exceeds maximum size of {} bytes",+ MAX_CUSTOMER_GLOBAL_ID_MIGRATION_FILE_SIZE+ ),+ }))+ } else {+ let mut reader = csv::ReaderBuilder::new()+ .trim(csv::Trim::All)+ .from_reader(csv_bytes);+ let headers =+ reader+ .headers()+ .change_context(errors::ApiErrorResponse::InvalidRequestData {+ message: "CSV must include header: merchant_id,customer_id".to_string(),+ })?;++ if headers.len() != 2+ || headers.get(0) != Some("merchant_id")+ || headers.get(1) != Some("customer_id")+ {+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message: "CSV must include header: merchant_id,customer_id".to_string(),+ }))+ } else {+ reader+ .records()+ .enumerate()+ .map(|(index, record)| {+ if index >= MAX_CUSTOMER_GLOBAL_ID_MIGRATION_RECORDS {+ Err(report!(errors::ApiErrorResponse::InvalidRequestData {+ message: format!(+ "CSV file exceeds maximum record count of {}",+ MAX_CUSTOMER_GLOBAL_ID_MIGRATION_RECORDS+ ),+ }))+ } else {+ let row_number = index + 2;+ let row = record+ .map_err(|error| {+ Box::new(invalid_csv_row_result(+ row_number,+ None,+ None,+ format!("Invalid CSV row: {error}"),+ ))+ })+ .and_then(|record| {+ parse_customer_global_id_migration_record(row_number, &record)+ });+ Ok(row)+ }+ })+ .collect()+ }+ }+}++fn parse_customer_global_id_migration_record(+ row_number: usize,+ record: &csv::StringRecord,+) -> MigrationStepResult<MigrationRow<Parsed>> {+ let raw_merchant_id = record+ .get(0)+ .map(str::trim)+ .filter(|value| !value.is_empty());+ let raw_customer_id = record+ .get(1)+ .map(str::trim)+ .filter(|value| !value.is_empty());++ let merchant_id = raw_merchant_id+ .map(|value| id_type::MerchantId::wrap(value.to_owned()).ok())+ .unwrap_or(None);+ let customer_id = raw_customer_id+ .map(|value| id_type::CustomerId::wrap(value.to_owned()).ok())+ .unwrap_or(None);++ match (record.len() == 2, merchant_id, customer_id) {+ (true, Some(merchant_id), Some(customer_id)) => {+ Ok(MigrationRow::new(row_number, merchant_id, customer_id))+ }+ (_, merchant_id, customer_id) => Err(Box::new(invalid_csv_row_result(+ row_number,+ merchant_id,+ customer_id,+ "CSV row must contain valid merchant_id and customer_id values".to_string(),+ ))),+ }+}++fn invalid_csv_row_result(+ row_number: usize,+ merchant_id: Option<id_type::MerchantId>,+ customer_id: Option<id_type::CustomerId>,+ message: String,+) -> CustomerGlobalIdMigrationRowResult {+ CustomerGlobalIdMigrationRowResult {+ row_number,+ merchant_id,+ customer_id,+ status: CustomerGlobalIdMigrationStatus::InvalidCsvRow,+ old_id: None,+ new_id: None,+ message,+ }+}++struct Parsed;+struct Fetched;+struct V1Verified;+struct NeedsUpdate;+struct Generated;++struct MigrationRow<State> {+ row_number: usize,+ merchant_id: id_type::MerchantId,+ customer_id: id_type::CustomerId,+ old_id: Option<String>,+ version: Option<ApiVersion>,+ new_id: Option<id_type::GlobalCustomerId>,+ update_status: Option<CustomerGlobalIdMigrationStatus>,+ state: PhantomData<State>,+}++impl MigrationRow<Parsed> {+ fn new(+ row_number: usize,+ merchant_id: id_type::MerchantId,+ customer_id: id_type::CustomerId,+ ) -> Self {+ Self {+ row_number,+ merchant_id,+ customer_id,+ old_id: None,+ version: None,+ new_id: None,+ update_status: None,+ state: PhantomData,+ }+ }++ async fn fetch(self, state: &SessionState) -> MigrationStepResult<MigrationRow<Fetched>> {+ match state+ .store+ .find_customer_for_global_id_migration(&self.customer_id, &self.merchant_id)+ .await+ {+ Ok(row) => {+ let mut next = self.transition::<Fetched>();+ next.old_id = row.id;+ next.version = Some(row.version);+ Ok(next)+ }+ Err(error)+ if matches!(+ error.current_context(),+ errors::StorageError::ValueNotFound(_)+ ) =>+ {+ Err(Box::new(self.result(+ CustomerGlobalIdMigrationStatus::NotFound,+ None,+ "Customer not found for merchant_id and customer_id".to_string(),+ )))+ }+ Err(error) => Err(Box::new(self.result(+ CustomerGlobalIdMigrationStatus::UpdateFailed,+ None,+ format!("Failed to fetch customer for migration: {error:?}"),+ ))),+ }+ }+}++impl MigrationRow<Fetched> {+ fn verify_v1(self) -> MigrationStepResult<MigrationRow<V1Verified>> {+ match self.version {+ Some(ApiVersion::V1) => Ok(self.transition::<V1Verified>()),+ Some(_) => Err(Box::new(self.result(+ CustomerGlobalIdMigrationStatus::SkippedNonV1,+ None,+ "Customer is not a v1 row; skipping migration".to_string(),+ ))),+ None => Err(Box::new(self.result(+ CustomerGlobalIdMigrationStatus::UpdateFailed,+ None,+ "Customer version was not available for migration".to_string(),+ ))),+ }+ }+}++impl MigrationRow<V1Verified> {+ fn classify_current_id(self) -> MigrationStepResult<MigrationRow<NeedsUpdate>> {+ match self.old_id.as_deref() {+ Some(id) if is_global_customer_id_format(id) => Err(Box::new(self.result(+ CustomerGlobalIdMigrationStatus::AlreadyGlobalId,+ None,+ "Customer id is already in global id format".to_string(),+ ))),+ None => {+ let mut next = self.transition::<NeedsUpdate>();+ next.update_status = Some(CustomerGlobalIdMigrationStatus::UpdatedNullId);+ Ok(next)+ }+ Some(_) => {+ let mut next = self.transition::<NeedsUpdate>();+ next.update_status = Some(CustomerGlobalIdMigrationStatus::UpdatedNonGlobalId);+ Ok(next)+ }+ }+ }+}++impl MigrationRow<NeedsUpdate> {+ fn generate(self, state: &SessionState) -> MigrationRow<Generated> {+ let new_id = id_type::GlobalCustomerId::generate(&state.conf.cell_information.id);+ let mut next = self.transition::<Generated>();+ next.new_id = Some(new_id);+ next+ }+}++impl MigrationRow<Generated> {+ async fn update(self, state: &SessionState) -> CustomerGlobalIdMigrationRowResult {+ match self.new_id.clone() {+ Some(new_id) => match state+ .store+ .update_customer_global_id_for_migration(+ &self.customer_id,+ &self.merchant_id,+ new_id,+ )+ .await+ {+ Ok(_) => self.result(+ self.update_status+ .clone()+ .unwrap_or(CustomerGlobalIdMigrationStatus::UpdateFailed),+ self.new_id.as_ref(),+ "Customer id updated successfully".to_string(),+ ),+ Err(error) => self.result(+ CustomerGlobalIdMigrationStatus::UpdateFailed,+ self.new_id.as_ref(),+ format!("Failed to update customer id: {error:?}"),+ ),+ },+ None => self.result(+ CustomerGlobalIdMigrationStatus::UpdateFailed,+ None,+ "New customer global id was not generated".to_string(),+ ),+ }+ }+}++async fn process_fetched_row(+ row: MigrationStepResult<MigrationRow<Fetched>>,+ state: &SessionState,+) -> CustomerGlobalIdMigrationRowResult {+ match row {+ Ok(row) => match row+ .verify_v1()+ .and_then(MigrationRow::<V1Verified>::classify_current_id)+ {+ Ok(row) => row.generate(state).update(state).await,+ Err(result) => *result,+ },+ Err(result) => *result,+ }+}++impl<State> MigrationRow<State> {+ fn transition<NextState>(self) -> MigrationRow<NextState> {+ MigrationRow {+ row_number: self.row_number,+ merchant_id: self.merchant_id,+ customer_id: self.customer_id,+ old_id: self.old_id,+ version: self.version,+ new_id: self.new_id,+ update_status: self.update_status,+ state: PhantomData,+ }+ }++ fn result(+ &self,+ status: CustomerGlobalIdMigrationStatus,+ new_id: Option<&id_type::GlobalCustomerId>,+ message: String,+ ) -> CustomerGlobalIdMigrationRowResult {+ CustomerGlobalIdMigrationRowResult {+ row_number: self.row_number,+ merchant_id: Some(self.merchant_id.clone()),+ customer_id: Some(self.customer_id.clone()),+ status,+ old_id: self.old_id.clone(),+ new_id: new_id.map(|id| id.get_string_repr().to_owned()),+ message,+ }+ }+}++fn is_global_customer_id_format(id: &str) -> bool {+ let mut parts = id.split('_');+ match (parts.next(), parts.next(), parts.next(), parts.next()) {+ (Some(cell_id), Some(entity), Some(uuid), None) => {+ cell_id.len() == 5+ && cell_id+ .chars()+ .all(|character| character.is_ascii_lowercase() || character.is_ascii_digit())+ && entity == "cus"+ && uuid.len() == 32+ && uuid::Uuid::parse_str(uuid).is_ok()+ }+ _ => false,+ }+}++fn log_row_result(result: &CustomerGlobalIdMigrationRowResult) {+ logger::info!(+ row_number = result.row_number,+ merchant_id = ?result.merchant_id,+ customer_id = ?result.customer_id,+ old_id = ?result.old_id,+ new_id = ?result.new_id,+ status = ?result.status,+ message = result.message,+ "customer global id migration row processed"+ );+}diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex 7441865233..fa901ae856 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -123,6 +123,7 @@ impl From<Flow> for ApiIdentifier {| Flow::CustomersUpdate| Flow::CustomersDelete| Flow::CustomersGetMandates+ | Flow::CustomersGlobalIdMigration| Flow::CustomersList| Flow::CustomersListWithConstraints => Self::Customers,Flow::EphemeralKeyCreate | Flow::EphemeralKeyDelete => Self::Ephemeral,diff --git a/crates/router/src/types/storage/customers.rs b/crates/router/src/types/storage/customers.rsindex 6533a658da..74f0e42603 100644--- a/crates/router/src/types/storage/customers.rs+++ b/crates/router/src/types/storage/customers.rs@@ -1,3 +1,5 @@+#[cfg(feature = "v2")]+pub use diesel_models::customers::CustomerGlobalIdMigrationRow;pub use diesel_models::customers::{Customer, CustomerNew, CustomerUpdateInternal};#[cfg(feature = "v2")]diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 043244410a..e1f211e701 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -116,6 +116,8 @@ pub enum Flow {CustomersDelete,/// Customers get mandates flow.CustomersGetMandates,+ /// Customers global id migration flow.+ CustomersGlobalIdMigration,/// Create an Ephemeral Key.EphemeralKeyCreate,/// Delete an Ephemeral Key.diff --git a/crates/storage_impl/src/customers.rs b/crates/storage_impl/src/customers.rsindex 545e5a76b9..3909a6cdaf 100644--- a/crates/storage_impl/src/customers.rs+++ b/crates/storage_impl/src/customers.rs@@ -151,6 +151,31 @@ impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterSt})}+ #[cfg(feature = "v2")]+ #[instrument(skip_all)]+ async fn find_customer_for_global_id_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ ) -> CustomResult<customers::CustomerGlobalIdMigrationRow, StorageError> {+ self.router_store+ .find_customer_for_global_id_migration(customer_id, merchant_id)+ .await+ }++ #[cfg(feature = "v2")]+ #[instrument(skip_all)]+ async fn update_customer_global_id_for_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ new_id: id_type::GlobalCustomerId,+ ) -> CustomResult<customers::CustomerGlobalIdMigrationRow, StorageError> {+ self.router_store+ .update_customer_global_id_for_migration(customer_id, merchant_id, new_id)+ .await+ }+#[cfg(feature = "v1")]#[instrument(skip_all)]async fn update_customer_by_customer_id_merchant_id(@@ -620,6 +645,43 @@ impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {})}+ #[cfg(feature = "v2")]+ #[instrument(skip_all)]+ async fn find_customer_for_global_id_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ ) -> CustomResult<customers::CustomerGlobalIdMigrationRow, StorageError> {+ let conn = pg_connection_read(self).await?;+ customers::Customer::find_by_merchant_id_customer_id_for_global_id_migration(+ &conn,+ merchant_id,+ customer_id,+ )+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })+ }++ #[cfg(feature = "v2")]+ #[instrument(skip_all)]+ async fn update_customer_global_id_for_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ new_id: id_type::GlobalCustomerId,+ ) -> CustomResult<customers::CustomerGlobalIdMigrationRow, StorageError> {+ let conn = pg_connection_write(self).await?;+ customers::Customer::update_global_id_for_migration(&conn, merchant_id, customer_id, new_id)+ .await+ .map_err(|error| {+ let new_err = diesel_error_to_data_error(*error.current_context());+ error.change_context(new_err)+ })+ }+#[cfg(feature = "v1")]#[instrument(skip_all)]async fn update_customer_by_customer_id_merchant_id(@@ -891,6 +953,64 @@ impl domain::CustomerInterface for MockDb {todo!()}+ #[cfg(feature = "v2")]+ async fn find_customer_for_global_id_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ ) -> CustomResult<customers::CustomerGlobalIdMigrationRow, StorageError> {+ let customers = self.customers.lock().await;+ customers+ .iter()+ .find_map(|customer| {+ let row_customer_id = customer.customer_id.as_ref()?.get_string_repr();+ (customer.merchant_id == *merchant_id+ && row_customer_id == customer_id.get_string_repr())+ .then(|| customers::CustomerGlobalIdMigrationRow {+ merchant_id: customer.merchant_id.clone(),+ customer_id: Some(row_customer_id.to_owned()),+ id: Some(customer.id.get_string_repr().to_owned()),+ version: customer.version,+ })+ })+ .ok_or_else(|| StorageError::ValueNotFound("customer".to_string()).into())+ }++ #[cfg(feature = "v2")]+ async fn update_customer_global_id_for_migration(+ &self,+ customer_id: &id_type::CustomerId,+ merchant_id: &id_type::MerchantId,+ new_id: id_type::GlobalCustomerId,+ ) -> CustomResult<customers::CustomerGlobalIdMigrationRow, StorageError> {+ let mut customers = self.customers.lock().await;+ let customer = customers+ .iter_mut()+ .find(|customer| {+ customer.version == common_enums::ApiVersion::V1+ && customer.merchant_id == *merchant_id+ && customer+ .customer_id+ .as_ref()+ .is_some_and(|row_customer_id| {+ row_customer_id.get_string_repr() == customer_id.get_string_repr()+ })+ })+ .ok_or_else(|| StorageError::ValueNotFound("customer".to_string()))?;++ customer.id = new_id;++ Ok(customers::CustomerGlobalIdMigrationRow {+ merchant_id: customer.merchant_id.clone(),+ customer_id: customer+ .customer_id+ .as_ref()+ .map(|customer_id| customer_id.get_string_repr().to_owned()),+ id: Some(customer.id.get_string_repr().to_owned()),+ version: customer.version,+ })+ }+async fn list_customers_by_merchant_id(&self,merchant_id: &id_type::MerchantId,