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(blocklist): clone blocklist entries across business profiles (#14283)
Ayush Anandafd92843521c
diff --git a/api-reference/docs.json b/api-reference/docs.jsonindex aa580cf1ac..24c89eb081 100644--- a/api-reference/docs.json+++ b/api-reference/docs.json@@ -283,7 +283,8 @@"v1/blocklist/blocklist--batch-upload","v1/blocklist/blocklist--batch-list","v1/blocklist/blocklist--batch-status",- "v1/blocklist/blocklist--export-create"+ "v1/blocklist/blocklist--export-create",+ "v1/blocklist/blocklist--clone"]},{diff --git a/api-reference/v1/blocklist/blocklist--clone.mdx b/api-reference/v1/blocklist/blocklist--clone.mdxnew file mode 100644index 0000000000..3809ba45eb--- /dev/null+++ b/api-reference/v1/blocklist/blocklist--clone.mdx@@ -0,0 +1,3 @@+---+openapi: post /blocklist/clone+---diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.jsonindex c684a51400..73a942908f 100644--- a/api-reference/v1/openapi_spec_v1.json+++ b/api-reference/v1/openapi_spec_v1.json@@ -6985,6 +6985,9 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []}]},@@ -7032,6 +7035,12 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []+ },+ {+ "publishable_key": []}]},@@ -7080,6 +7089,9 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []}]}@@ -7119,6 +7131,9 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []}]}@@ -7168,6 +7183,9 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []}]}@@ -7217,6 +7235,9 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []}]}@@ -7268,6 +7289,9 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []}]},@@ -7304,7 +7328,7 @@{"name": "job_type","in": "query",- "description": "Restricts the listing to `upload` or `export` jobs. Both kinds are returned when omitted, newest first.",+ "description": "Restricts the listing to `upload`, `export`, or `profile_clone` jobs. All kinds are returned when omitted, newest first.","required": false,"schema": {"allOf": [@@ -7341,6 +7365,9 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []}]}@@ -7380,6 +7407,9 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []}]}@@ -7420,6 +7450,67 @@"security": [{"api_key": []+ },+ {+ "jwt_key": []+ }+ ]+ }+ },+ "/blocklist/clone": {+ "post": {+ "tags": [+ "Blocklist"+ ],+ "summary": "Blocklist - Clone Entries",+ "description": "Copies a business profile's blocklist entries onto other profiles of the same merchant. The\ncopy runs as one background job whose process tracker clones onto the targets one at a time.\nPoll `/blocklist/batch/{job_id}` for per-target progress in the job metadata.",+ "operationId": "Clone blocklist entries across profiles",+ "parameters": [+ {+ "name": "X-Profile-Id",+ "in": "header",+ "description": "Source profile whose entries are copied; it also owns the clone job. Required when the authenticated dashboard session does not provide a profile context",+ "required": false,+ "schema": {+ "type": "string",+ "nullable": true+ }+ }+ ],+ "requestBody": {+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CloneBlocklistEntriesRequest"+ }+ }+ },+ "required": true+ },+ "responses": {+ "200": {+ "description": "One background job was started; it clones onto the target profiles one at a time",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/CloneBlocklistEntriesResponse"+ }+ }+ }+ },+ "400": {+ "description": "Missing profile context, no targets given, or a target is the source profile"+ },+ "404": {+ "description": "The source or a target profile does not belong to the merchant"+ }+ },+ "security": [+ {+ "api_key": []+ },+ {+ "jwt_key": []}]}@@ -15868,12 +15959,18 @@"merchant_id": {"type": "string"},+ "profile_id": {+ "type": "string",+ "description": "The profile that owns this job; for a clone job, the profile whose entries are copied.",+ "example": "pro_abcdefghijklmnop",+ "nullable": true+ },"job_type": {"$ref": "#/components/schemas/BatchBlocklistJobType"},"file_name": {"type": "string",- "description": "The file the merchant uploaded, or the name the export downloads as.",+ "description": "The file the merchant uploaded, or the name the export downloads as. Clone jobs return\n`null`.","nullable": true},"status": {@@ -15894,6 +15991,14 @@"format": "int32","minimum": 0},+ "metadata": {+ "allOf": [+ {+ "$ref": "#/components/schemas/ProfileCloneJobMetadata"+ }+ ],+ "nullable": true+ },"created_at": {"type": "string","format": "date-time"@@ -15930,10 +16035,11 @@},"BatchBlocklistJobType": {"type": "string",- "description": "Distinguishes a bulk upload job from a CSV export job in the `batch_blocklist_jobs` table.",+ "description": "Distinguishes bulk upload, CSV export, and profile clone jobs.","enum": ["upload",- "export"+ "export",+ "profile_clone"]},"BatchBlocklistUploadResponse": {@@ -18517,6 +18623,48 @@"type": "string","description": "For Client based calls, SDK will use the client_secret\\nin order to call /payment_methods\\nClient secret will be generated whenever a new\\npayment method is created"},+ "CloneBlocklistEntriesRequest": {+ "type": "object",+ "required": [+ "target_profile_ids"+ ],+ "properties": {+ "target_profile_ids": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "CloneBlocklistEntriesResponse": {+ "type": "object",+ "description": "Response for `POST /blocklist/clone`.",+ "required": [+ "source_profile_id",+ "job_id",+ "status",+ "target_profile_ids"+ ],+ "properties": {+ "source_profile_id": {+ "type": "string",+ "example": "pro_abcdefghijklmnop"+ },+ "job_id": {+ "type": "string"+ },+ "status": {+ "$ref": "#/components/schemas/BatchBlocklistJobStatus"+ },+ "target_profile_ids": {+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },"CollectionActions": {"type": "object","description": "Represents the legal or administrative actions that may be taken for non-payment, such as protest rules and automatic write-off timelines.",@@ -41804,6 +41952,50 @@},"additionalProperties": false},+ "ProfileCloneJobMetadata": {+ "type": "object",+ "description": "Progress of a profile-clone job across its target profiles.",+ "required": [+ "targets"+ ],+ "properties": {+ "targets": {+ "type": "array",+ "items": {+ "$ref": "#/components/schemas/ProfileCloneTargetMetadata"+ }+ }+ }+ },+ "ProfileCloneTargetMetadata": {+ "type": "object",+ "description": "Progress of one target profile within a profile-clone job.",+ "required": [+ "profile_id",+ "status",+ "processed_rows"+ ],+ "properties": {+ "profile_id": {+ "type": "string",+ "example": "pro_abcdefghijklmnop"+ },+ "status": {+ "$ref": "#/components/schemas/BatchBlocklistJobStatus"+ },+ "processed_rows": {+ "type": "integer",+ "format": "int32",+ "description": "Source entries handled so far for this target.",+ "minimum": 0+ },+ "error_message": {+ "type": "string",+ "description": "Present when this target's clone failed.",+ "nullable": true+ }+ }+ },"ProfileCreate": {"type": "object","properties": {diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rsindex 31d5019d31..449aa2538f 100644--- a/crates/api_models/src/blocklist.rs+++ b/crates/api_models/src/blocklist.rs@@ -1,4 +1,4 @@-use std::collections::BTreeMap;+use std::collections::{BTreeMap, HashSet};use common_enums::enums;use common_utils::events::ApiEventMetric;@@ -163,16 +163,23 @@ pub struct BatchBlocklistUploadResponse {pub struct BatchBlocklistJobStatusResponse {pub job_id: String,pub merchant_id: String,- /// Whether this job imported entries or exported them.+ /// The profile that owns this job; for a clone job, the profile whose entries are copied.+ #[schema(value_type = Option<String>, example = "pro_abcdefghijklmnop")]+ pub profile_id: Option<common_utils::id_type::ProfileId>,+ /// Whether this job imported, exported, or cloned entries.#[schema(value_type = BatchBlocklistJobType)]pub job_type: enums::BatchBlocklistJobType,- /// The file the merchant uploaded, or the name the export downloads as.+ /// The file the merchant uploaded, or the name the export downloads as. Clone jobs return+ /// `null`.pub file_name: Option<String>,#[schema(value_type = BatchBlocklistJobStatus)]pub status: enums::BatchBlocklistJobStatus,pub total_rows: u32,pub succeeded_rows: u32,pub failed_rows: u32,+ /// Per-target status and row progress of a profile-clone job. Upload and export jobs return+ /// `null`.+ pub metadata: Option<ProfileCloneJobMetadata>,#[serde(with = "common_utils::custom_serde::iso8601")]pub created_at: time::PrimitiveDateTime,#[serde(with = "common_utils::custom_serde::iso8601")]@@ -200,7 +207,7 @@ pub struct ListBatchBlocklistJobsQuery {/// The starting point within a list of objects#[serde(default)]pub offset: common_utils::types::list::PageOffset,- /// Restricts the listing to one kind of job. Both uploads and exports are returned when omitted.+ /// Restricts the listing to one kind of job. All kinds are returned when omitted.#[schema(value_type = Option<BatchBlocklistJobType>)]pub job_type: Option<enums::BatchBlocklistJobType>,}@@ -231,3 +238,60 @@ impl ApiEventMetric for BatchBlocklistJobStatusResponse {}impl ApiEventMetric for ListBatchBlocklistJobsQuery {}impl ApiEventMetric for ListBatchBlocklistJobsResponse {}impl ApiEventMetric for BlocklistExportResponse {}++/// Progress of a profile-clone job across its target profiles.+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct ProfileCloneJobMetadata {+ pub targets: Vec<ProfileCloneTargetMetadata>,+}++/// Progress of one target profile within a profile-clone job.+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct ProfileCloneTargetMetadata {+ #[schema(value_type = String, example = "pro_abcdefghijklmnop")]+ pub profile_id: common_utils::id_type::ProfileId,+ #[schema(value_type = BatchBlocklistJobStatus)]+ pub status: enums::BatchBlocklistJobStatus,+ /// Source entries handled so far for this target.+ pub processed_rows: u32,+ /// Present when this target's clone failed.+ pub error_message: Option<String>,+}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct CloneBlocklistEntriesRequest {+ #[schema(value_type = Vec<String>)]+ pub target_profile_ids: HashSet<common_utils::id_type::ProfileId>,+}++impl CloneBlocklistEntriesRequest {+ /// The checks that need nothing but the request and its source; whether each profile belongs+ /// to the merchant is settled later, against the merchant's profiles.+ pub fn validate(+ &self,+ source_profile_id: &common_utils::id_type::ProfileId,+ ) -> Result<(), String> {+ (!self.target_profile_ids.is_empty())+ .then_some(())+ .ok_or_else(|| "target_profile_ids must contain at least one profile".to_string())?;++ (!self.target_profile_ids.contains(source_profile_id))+ .then_some(())+ .ok_or_else(|| "target_profile_ids must not contain the source profile".to_string())+ }+}++/// Response for `POST /blocklist/clone`.+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]+pub struct CloneBlocklistEntriesResponse {+ #[schema(value_type = String, example = "pro_abcdefghijklmnop")]+ pub source_profile_id: common_utils::id_type::ProfileId,+ pub job_id: String,+ #[schema(value_type = BatchBlocklistJobStatus)]+ pub status: enums::BatchBlocklistJobStatus,+ #[schema(value_type = Vec<String>)]+ pub target_profile_ids: Vec<common_utils::id_type::ProfileId>,+}++impl ApiEventMetric for CloneBlocklistEntriesRequest {}+impl ApiEventMetric for CloneBlocklistEntriesResponse {}diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rsindex de0451d423..97b98924e0 100644--- a/crates/common_enums/src/enums.rs+++ b/crates/common_enums/src/enums.rs@@ -11376,6 +11376,7 @@ pub enum ProcessTrackerRunner {NetworkTokenizationWorkflow,OfferEngineNotifyWorkflow,BlocklistExportWorkflow,+ BlocklistProfileCloneWorkflow,}#[derive(@@ -12052,7 +12053,7 @@ pub enum BatchBlocklistJobStatus {Failed,}-/// Distinguishes a bulk upload job from a CSV export job in the `batch_blocklist_jobs` table.+/// Distinguishes bulk upload, CSV export, and profile clone jobs.#[derive(Clone,Copy,@@ -12071,6 +12072,7 @@ pub enum BatchBlocklistJobStatus {pub enum BatchBlocklistJobType {Upload,Export,+ ProfileClone,}#[derive(diff --git a/crates/diesel_models/src/batch_blocklist_job.rs b/crates/diesel_models/src/batch_blocklist_job.rsindex 6697a3e4c1..610499b0d2 100644--- a/crates/diesel_models/src/batch_blocklist_job.rs+++ b/crates/diesel_models/src/batch_blocklist_job.rs@@ -1,6 +1,8 @@use common_enums::{BatchBlocklistJobStatus, BatchBlocklistJobType};use common_utils::id_type;-use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};+use diesel::{+ sql_types::Jsonb, AsChangeset, AsExpression, Identifiable, Insertable, Queryable, Selectable,+};use serde::{Deserialize, Serialize};use time::PrimitiveDateTime;@@ -25,6 +27,7 @@ pub struct BatchBlocklistJob {pub file_key: Option<String>,pub error_message: Option<String>,pub expires_at: Option<PrimitiveDateTime>,+ pub metadata: Option<BlocklistProfileCloneJobMetadata>,}#[derive(Clone, Debug, Insertable, Deserialize, Serialize)]@@ -41,6 +44,7 @@ pub struct BatchBlocklistJobNew {pub profile_id: id_type::ProfileId,pub job_type: BatchBlocklistJobType,pub file_name: Option<String>,+ pub metadata: Option<BlocklistProfileCloneJobMetadata>,}#[derive(Clone, Debug, AsChangeset)]@@ -53,5 +57,24 @@ pub struct BatchBlocklistJobUpdate {pub file_key: Option<String>,pub error_message: Option<String>,pub expires_at: Option<PrimitiveDateTime>,+ pub metadata: Option<BlocklistProfileCloneJobMetadata>,pub updated_at: PrimitiveDateTime,}++/// Job-level progress for a multi-target profile clone, one entry per target. The generic row+/// counters on the job stay at zero.+#[derive(Clone, Debug, Deserialize, Serialize, AsExpression)]+#[diesel(sql_type = Jsonb)]+pub struct BlocklistProfileCloneJobMetadata {+ pub targets: Vec<BlocklistProfileCloneTargetMetadata>,+}++common_utils::impl_to_sql_from_sql_json!(BlocklistProfileCloneJobMetadata);++#[derive(Clone, Debug, Deserialize, Serialize)]+pub struct BlocklistProfileCloneTargetMetadata {+ pub profile_id: id_type::ProfileId,+ pub status: BatchBlocklistJobStatus,+ pub processed_rows: i32,+ pub error_message: Option<String>,+}diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rsindex 6a596f3702..132a6faf7d 100644--- a/crates/diesel_models/src/schema.rs+++ b/crates/diesel_models/src/schema.rs@@ -212,6 +212,7 @@ diesel::table! {file_key -> Nullable<Varchar>,error_message -> Nullable<Text>,expires_at -> Nullable<Timestamp>,+ metadata -> Nullable<Jsonb>,}}diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rsindex 5d1f2599f6..491d7ddd07 100644--- a/crates/diesel_models/src/schema_v2.rs+++ b/crates/diesel_models/src/schema_v2.rs@@ -212,6 +212,7 @@ diesel::table! {file_key -> Nullable<Varchar>,error_message -> Nullable<Text>,expires_at -> Nullable<Timestamp>,+ metadata -> Nullable<Jsonb>,}}diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rsindex 0aff896be9..979b335976 100644--- a/crates/openapi/src/openapi.rs+++ b/crates/openapi/src/openapi.rs@@ -213,6 +213,7 @@ Never share your secret api keys. Keep them guarded and secure.routes::blocklist::get_batch_blocklist_job_status,routes::blocklist::list_batch_blocklist_jobs,routes::blocklist::create_blocklist_export,+ routes::blocklist::clone_blocklist_entries,// Routes for payoutsroutes::payouts::payouts_create,@@ -1047,6 +1048,10 @@ Never share your secret api keys. Keep them guarded and secure.api_models::blocklist::ListBatchBlocklistJobsResponse,api_models::blocklist::BlocklistRowError,api_models::blocklist::BlocklistExportResponse,+ api_models::blocklist::CloneBlocklistEntriesRequest,+ api_models::blocklist::CloneBlocklistEntriesResponse,+ api_models::blocklist::ProfileCloneJobMetadata,+ api_models::blocklist::ProfileCloneTargetMetadata,api_models::enums::BatchBlocklistJobStatus,api_models::enums::BatchBlocklistJobType,api_models::enums::BlocklistDataKind,diff --git a/crates/openapi/src/routes/blocklist.rs b/crates/openapi/src/routes/blocklist.rsindex 5530905518..cae55b5f72 100644--- a/crates/openapi/src/routes/blocklist.rs+++ b/crates/openapi/src/routes/blocklist.rs@@ -14,7 +14,7 @@),tag = "Blocklist",operation_id = "Count blocked fingerprints of a particular kind",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn get_blocklist_count() {}@@ -34,7 +34,7 @@ pub async fn get_blocklist_count() {}),tag = "Blocklist",operation_id = "Look up whether a value is blocked",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn lookup_blocklist_entry() {}@@ -50,7 +50,7 @@ pub async fn lookup_blocklist_entry() {}),tag = "Blocklist",operation_id = "Toggle blocklist guard for a particular merchant",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn toggle_blocklist_guard() {}@@ -70,7 +70,7 @@ pub async fn toggle_blocklist_guard() {}),tag = "Blocklist",operation_id = "Block a Fingerprint",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn add_entry_to_blocklist() {}@@ -91,7 +91,7 @@ pub async fn add_entry_to_blocklist() {}),tag = "Blocklist",operation_id = "Unblock a Fingerprint",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn remove_entry_from_blocklist() {}@@ -111,7 +111,7 @@ pub async fn remove_entry_from_blocklist() {}),tag = "Blocklist",operation_id = "List Blocked fingerprints of a particular kind",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = []), ("publishable_key" = [])))]pub async fn list_blocked_payment_methods() {}@@ -139,7 +139,7 @@ pub async fn list_blocked_payment_methods() {}),tag = "Blocklist",operation_id = "Upload a batch blocklist CSV",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn upload_batch_blocklist() {}@@ -158,7 +158,7 @@ pub async fn upload_batch_blocklist() {}),tag = "Blocklist",operation_id = "Get batch blocklist job status",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn get_batch_blocklist_job_status() {}@@ -169,7 +169,7 @@ pub async fn get_batch_blocklist_job_status() {}("limit" = Option<u8>, Query, description = "Maximum number of jobs to return (default 10, max 100)"),("offset" = Option<u32>, Query, description = "Zero-based offset for pagination (default 0)"),("job_type" = Option<BatchBlocklistJobType>, Query, description = "Restricts the listing to \- `upload` or `export` jobs. Both kinds are returned when omitted, newest first."),+ `upload`, `export`, or `profile_clone` jobs. All kinds are returned when omitted, newest first."),("X-Profile-Id" = Option<String>, Header, description = "Restricts the listing to jobs run \for this business profile, plus jobs that predate profile scoping. When no profile can be \resolved, all of the merchant's jobs are returned, as before."),@@ -181,7 +181,7 @@ pub async fn get_batch_blocklist_job_status() {}),tag = "Blocklist",operation_id = "List batch blocklist jobs",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn list_batch_blocklist_jobs() {}@@ -198,6 +198,29 @@ pub async fn list_batch_blocklist_jobs() {}),tag = "Blocklist",operation_id = "Start a blocklist CSV export",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn create_blocklist_export() {}++/// Blocklist - Clone Entries+///+/// Copies a business profile's blocklist entries onto other profiles of the same merchant. The+/// copy runs as one background job whose process tracker clones onto the targets one at a time.+/// Poll `/blocklist/batch/{job_id}` for per-target progress in the job metadata.+#[utoipa::path(+ post,+ path = "/blocklist/clone",+ request_body = CloneBlocklistEntriesRequest,+ params(+ ("X-Profile-Id" = Option<String>, Header, description = "Source profile whose entries are copied; it also owns the clone job. Required when the authenticated dashboard session does not provide a profile context")+ ),+ responses(+ (status = 200, description = "One background job was started; it clones onto the target profiles one at a time", body = CloneBlocklistEntriesResponse),+ (status = 400, description = "Missing profile context, no targets given, or a target is the source profile"),+ (status = 404, description = "The source or a target profile does not belong to the merchant"),+ ),+ tag = "Blocklist",+ operation_id = "Clone blocklist entries across profiles",+ security(("api_key" = []), ("jwt_key" = []))+)]+pub async fn clone_blocklist_entries() {}diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rsindex 3655f9d365..96615a04ce 100644--- a/crates/router/src/bin/scheduler.rs+++ b/crates/router/src/bin/scheduler.rs@@ -426,6 +426,21 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {)}}+ storage::ProcessTrackerRunner::BlocklistProfileCloneWorkflow => {+ #[cfg(feature = "v1")]+ {+ Ok(Box::new(+ workflows::blocklist_profile_clone::BlocklistProfileCloneWorkflow,+ ))+ }+ #[cfg(feature = "v2")]+ {+ Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow))+ .attach_printable(+ "Cannot run blocklist profile clone workflow when v1 feature is disabled",+ )+ }+ }}};diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rsindex b09e976641..6759923f2d 100644--- a/crates/router/src/core/blocklist.rs+++ b/crates/router/src/core/blocklist.rs@@ -1,4 +1,5 @@pub mod batch;+pub mod clone;pub mod export;pub mod transformers;pub mod utils;@@ -135,3 +136,14 @@ pub async fn create_blocklist_export(.await.map(services::ApplicationResponse::Json)}++pub async fn clone_blocklist_entries(+ state: SessionState,+ platform: domain::Platform,+ profile_id: Option<common_utils::id_type::ProfileId>,+ body: api_blocklist::CloneBlocklistEntriesRequest,+) -> RouterResponse<api_blocklist::CloneBlocklistEntriesResponse> {+ clone::clone_blocklist_entries(&state, &platform, profile_id, body)+ .await+ .map(services::ApplicationResponse::Json)+}diff --git a/crates/router/src/core/blocklist/batch.rs b/crates/router/src/core/blocklist/batch.rsindex 26ee91254c..5ceae987b0 100644--- a/crates/router/src/core/blocklist/batch.rs+++ b/crates/router/src/core/blocklist/batch.rs@@ -16,7 +16,7 @@ use crate::{},logger,routes::SessionState,- types::{domain, storage},+ types::{domain, storage, transformers::ForeignTryFrom},};const CHUNK_SIZE: usize = 2_000;@@ -431,6 +431,7 @@ pub async fn initiate_batch_blocklist_upload(profile_id: profile_id.clone(),job_type: common_enums::BatchBlocklistJobType::Upload,file_name,+ metadata: None,};state@@ -581,6 +582,7 @@ fn to_job_status_response(Ok(api_blocklist::BatchBlocklistJobStatusResponse {job_id: job.id,merchant_id: job.merchant_id.get_string_repr().to_owned(),+ profile_id: job.profile_id,job_type: job.job_type.unwrap_or(common_enums::BatchBlocklistJobType::Upload),@@ -597,11 +599,43 @@ fn to_job_status_response(expires_at: job.expires_at,downloadable,error_message: job.error_message,+ metadata: job+ .metadata+ .map(storage::BlocklistProfileCloneJobMetadata::from)+ .map(api_blocklist::ProfileCloneJobMetadata::foreign_try_from)+ .transpose()?,download_url: None,download_url_expires_at: None,})}+impl ForeignTryFrom<storage::BlocklistProfileCloneJobMetadata>+ for api_blocklist::ProfileCloneJobMetadata+{+ type Error = error_stack::Report<errors::ApiErrorResponse>;++ fn foreign_try_from(+ metadata: storage::BlocklistProfileCloneJobMetadata,+ ) -> Result<Self, Self::Error> {+ let targets = metadata+ .targets+ .into_iter()+ .map(|target| {+ u32::try_from(target.processed_rows)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .map(|processed_rows| api_blocklist::ProfileCloneTargetMetadata {+ profile_id: target.profile_id,+ status: target.status,+ processed_rows,+ error_message: target.error_message,+ })+ })+ .collect::<RouterResult<Vec<_>>>()?;++ Ok(Self { targets })+ }+}+/// Returns a paginated list of batch blocklist jobs for a merchant along with the total count.#[instrument(skip_all, fields(flow = ?router_env::Flow::ListBatchBlocklistJobs))]pub async fn list_batch_blocklist_jobs(diff --git a/crates/router/src/core/blocklist/clone.rs b/crates/router/src/core/blocklist/clone.rsnew file mode 100644index 0000000000..8fbd21ed05--- /dev/null+++ b/crates/router/src/core/blocklist/clone.rs@@ -0,0 +1,236 @@+//! Copying a business profile's blocklist entries onto its sibling profiles.+//!+//! A profile can hold a hundred thousand entries, so the copy runs as one background job whose+//! process tracker copies onto the target profiles one at a time, rather than inline.+use std::collections::HashSet;++use api_models::blocklist as api_blocklist;+use common_utils::{date_time, ext_traits::OptionExt, id_type};+use error_stack::ResultExt;+use router_env::{instrument, tracing};++use crate::{+ core::errors::{self, RouterResult, StorageErrorExt},+ logger,+ routes::SessionState,+ types::{domain, storage},+};++const BLOCKLIST_CLONE_TASK: &str = "BLOCKLIST_PROFILE_CLONE";+const BLOCKLIST_CLONE_TAGS: [&str; 2] = ["BLOCKLIST", "CLONE"];+/// Matches the export's page size — both walk the same table the same way.+pub(crate) const CLONE_PAGE_SIZE: i64 = 5_000;++/// Loads the merchant's profiles once and checks the source and every target against them, rather+/// than reading each profile separately. Any profile outside the merchant fails the whole request.+async fn resolve_clone_targets(+ state: &SessionState,+ processor: &domain::Processor,+ source_profile_id: &id_type::ProfileId,+ target_profile_ids: &HashSet<id_type::ProfileId>,+) -> RouterResult<Vec<id_type::ProfileId>> {+ let merchant_profile_ids = state+ .store+ .list_profile_by_merchant_id(processor.get_key_store(), processor.get_account().get_id())+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to list the merchant's business profiles")?+ .into_iter()+ .map(|profile| profile.get_id().clone())+ .collect::<HashSet<_>>();++ merchant_profile_ids+ .contains(source_profile_id)+ .then_some(())+ .ok_or(errors::ApiErrorResponse::ProfileNotFound {+ id: source_profile_id.get_string_repr().to_owned(),+ })?;++ target_profile_ids+ .iter()+ .map(|target_profile_id| -> RouterResult<id_type::ProfileId> {+ merchant_profile_ids+ .contains(target_profile_id)+ .then(|| target_profile_id.clone())+ .ok_or(+ errors::ApiErrorResponse::ProfileNotFound {+ id: target_profile_id.get_string_repr().to_owned(),+ }+ .into(),+ )+ })+ .collect()+}++/// Creates one job for the request, with a single process tracker that clones onto the targets in+/// order.+#[instrument(skip_all, fields(flow = ?router_env::Flow::CloneBlocklistEntries))]+pub async fn clone_blocklist_entries(+ state: &SessionState,+ platform: &domain::Platform,+ source_profile_id: Option<id_type::ProfileId>,+ request: api_blocklist::CloneBlocklistEntriesRequest,+) -> RouterResult<api_blocklist::CloneBlocklistEntriesResponse> {+ let processor = platform.get_processor();++ let source_profile_id = source_profile_id+ .get_required_value("profile_id")+ .change_context(errors::ApiErrorResponse::MissingRequiredField {+ field_name: "profile_id".into(),+ })?;++ request+ .validate(&source_profile_id)+ .map_err(|message| errors::ApiErrorResponse::InvalidRequestData { message })?;++ let targets = resolve_clone_targets(+ state,+ processor,+ &source_profile_id,+ &request.target_profile_ids,+ )+ .await?;++ let job_id = enqueue_clone_job(state, platform, &source_profile_id, &targets).await?;++ Ok(api_blocklist::CloneBlocklistEntriesResponse {+ source_profile_id,+ job_id,+ status: common_enums::BatchBlocklistJobStatus::Initiated,+ target_profile_ids: targets,+ })+}++/// Creates the job row and the single process tracker that clones onto every target in order. The+/// job's generic row counters intentionally stay at zero; per-target status and progress live in+/// its metadata.+async fn enqueue_clone_job(+ state: &SessionState,+ platform: &domain::Platform,+ source_profile_id: &id_type::ProfileId,+ targets: &[id_type::ProfileId],+) -> RouterResult<String> {+ let processor_merchant_id = platform.get_processor().get_account().get_id();+ let job_id = common_utils::generate_id(crate::consts::ID_LENGTH, "blkclone");+ let now = date_time::now();+ let target_profile_ids = targets.to_vec();++ let metadata = storage::BlocklistProfileCloneJobMetadata {+ targets: target_profile_ids+ .iter()+ .map(|profile_id| storage::BlocklistProfileCloneTargetMetadata {+ profile_id: profile_id.clone(),+ status: common_enums::BatchBlocklistJobStatus::Initiated,+ processed_rows: 0,+ error_message: None,+ })+ .collect(),+ };++ let job_new = storage::BatchBlocklistJobNew {+ id: job_id.clone(),+ merchant_id: processor_merchant_id.clone(),+ status: common_enums::BatchBlocklistJobStatus::Initiated,+ total_rows: 0,+ succeeded_rows: 0,+ failed_rows: 0,+ created_at: now,+ updated_at: now,+ profile_id: source_profile_id.clone(),+ job_type: common_enums::BatchBlocklistJobType::ProfileClone,+ file_name: None,+ metadata: Some(metadata.into()),+ };++ state+ .store+ .insert_batch_blocklist_job(job_new)+ .await+ .to_duplicate_response(errors::ApiErrorResponse::InternalServerError)?;++ let tracking_data = storage::BlocklistProfileCloneTrackingData {+ job_id: job_id.clone(),+ merchant_id: platform.get_provider().get_account().get_id().clone(),+ processor_merchant_id: Some(processor_merchant_id.clone()),+ source_profile_id: source_profile_id.clone(),+ target_profile_ids,+ current_target: 0,+ snapshot_at: now,+ draining_legacy_rows: false,+ last_fingerprint_id: String::new(),+ processed_rows: 0,+ };++ let process_tracker_entry = storage::ProcessTrackerNew::new(+ job_id.clone(),+ BLOCKLIST_CLONE_TASK,+ storage::ProcessTrackerRunner::BlocklistProfileCloneWorkflow,+ BLOCKLIST_CLONE_TAGS,+ tracking_data,+ None,+ now,+ common_types::consts::API_VERSION,+ common_enums::ApplicationSource::Main,+ )+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to create ProcessTrackerNew for a blocklist profile clone")?;++ match state.store.insert_process(process_tracker_entry).await {+ Ok(_) => {+ logger::info!(+ job_id = %job_id,+ source_profile_id = ?source_profile_id,+ target_count = targets.len(),+ "Blocklist profile clone job initiated"+ );+ Ok(job_id)+ }+ Err(error) => {+ state+ .store+ .update_batch_blocklist_job_by_id_merchant_id(+ &job_id,+ processor_merchant_id.get_string_repr(),+ storage::BatchBlocklistJobUpdate {+ status: Some(common_enums::BatchBlocklistJobStatus::Failed),+ succeeded_rows: None,+ failed_rows: None,+ total_rows: None,+ file_key: None,+ error_message: Some("Failed to enqueue the clone process".to_string()),+ expires_at: None,+ metadata: None,+ updated_at: date_time::now(),+ },+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable(+ "Failed to mark an unenqueued blocklist profile clone job failed",+ )?;+ Err(error)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to enqueue the blocklist profile clone process")+ }+ }+}++/// Rewrites one source row as an insert against the target profile. `created_by` is carried over+/// rather than restamped with the cloning operator: it records who originally blocked the entry.+/// `created_at` is refreshed because listings are ordered by it.+pub(crate) fn to_target_entry(+ entry: storage::Blocklist,+ target_profile_id: &id_type::ProfileId,+ created_at: time::PrimitiveDateTime,+) -> storage::BlocklistNew {+ storage::BlocklistNew {+ merchant_id: entry.merchant_id,+ fingerprint_id: entry.fingerprint_id,+ data_kind: entry.data_kind,+ metadata: entry.metadata,+ created_at,+ processor_merchant_id: entry.processor_merchant_id,+ created_by: entry.created_by,+ profile_id: Some(target_profile_id.clone()),+ }+}diff --git a/crates/router/src/core/blocklist/export.rs b/crates/router/src/core/blocklist/export.rsindex 27b4390602..610e320a4f 100644--- a/crates/router/src/core/blocklist/export.rs+++ b/crates/router/src/core/blocklist/export.rs@@ -102,6 +102,7 @@ pub async fn initiate_blocklist_export(profile_id: profile_id.clone(),job_type: common_enums::BatchBlocklistJobType::Export,file_name: Some(file_name.clone()),+ metadata: None,};statediff --git a/crates/router/src/db/batch_blocklist_job.rs b/crates/router/src/db/batch_blocklist_job.rsindex 289fdc6b8c..a7cfe046de 100644--- a/crates/router/src/db/batch_blocklist_job.rs+++ b/crates/router/src/db/batch_blocklist_job.rs@@ -26,6 +26,60 @@ fn matches_job_scope(})}+fn apply_profile_clone_target_update(+ job: &mut storage::BatchBlocklistJob,+ profile_id: &common_utils::id_type::ProfileId,+ update: storage::BlocklistProfileCloneTargetUpdate,+) -> Result<(), errors::StorageError> {+ let mut metadata = job.metadata.clone().ok_or_else(|| {+ errors::StorageError::InvalidDataFormat("profile clone job is missing metadata".to_string())+ })?;++ let target = metadata+ .targets+ .iter_mut()+ .find(|target| target.profile_id == *profile_id)+ .ok_or_else(|| {+ errors::StorageError::ValueNotFound(format!(+ "Profile clone target {profile_id:?} not found in job {}",+ job.id+ ))+ })?;++ target.status = update.status;+ target.processed_rows = update.processed_rows;+ target.error_message = update.error_message;++ let all_terminal = metadata.targets.iter().all(|target| {+ matches!(+ target.status,+ common_enums::BatchBlocklistJobStatus::Completed+ | common_enums::BatchBlocklistJobStatus::Failed+ )+ });+ let any_failed = metadata+ .targets+ .iter()+ .any(|target| target.status == common_enums::BatchBlocklistJobStatus::Failed);+ let any_started = metadata+ .targets+ .iter()+ .any(|target| target.status != common_enums::BatchBlocklistJobStatus::Initiated);++ job.status = match (all_terminal, any_failed, any_started) {+ (true, true, _) => common_enums::BatchBlocklistJobStatus::Failed,+ (true, false, _) => common_enums::BatchBlocklistJobStatus::Completed,+ (false, _, true) => common_enums::BatchBlocklistJobStatus::Processing,+ (false, _, false) => common_enums::BatchBlocklistJobStatus::Initiated,+ };+ job.error_message = (all_terminal && any_failed)+ .then(|| "One or more profile clone processes failed".to_string());+ job.metadata = Some(metadata);+ job.updated_at = common_utils::date_time::now();++ Ok(())+}+#[async_trait::async_trait]pub trait BatchBlocklistJobInterface {async fn insert_batch_blocklist_job(@@ -56,6 +110,14 @@ pub trait BatchBlocklistJobInterface {update: storage::BatchBlocklistJobUpdate,) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError>;+ async fn update_profile_clone_job_target(+ &self,+ id: &str,+ merchant_id: &str,+ profile_id: &common_utils::id_type::ProfileId,+ update: storage::BlocklistProfileCloneTargetUpdate,+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError>;+async fn count_batch_blocklist_jobs_by_merchant_id(&self,merchant_id: &str,@@ -152,6 +214,42 @@ impl BatchBlocklistJobInterface for Store {.map_err(|error| report!(errors::StorageError::from(error)))}+ #[instrument(skip_all)]+ async fn update_profile_clone_job_target(+ &self,+ id: &str,+ merchant_id: &str,+ profile_id: &common_utils::id_type::ProfileId,+ update: storage::BlocklistProfileCloneTargetUpdate,+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {+ let conn = connection::pg_connection_write(self).await?;+ let mut job = storage::BatchBlocklistJob::find_by_id_merchant_id(&conn, id, merchant_id)+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))?;++ apply_profile_clone_target_update(&mut job, profile_id, update)+ .map_err(|error| report!(error))?;++ storage::BatchBlocklistJob::update_by_id_merchant_id(+ &conn,+ id,+ merchant_id,+ storage::BatchBlocklistJobUpdate {+ status: Some(job.status),+ succeeded_rows: None,+ failed_rows: None,+ total_rows: None,+ file_key: None,+ error_message: job.error_message,+ expires_at: None,+ metadata: job.metadata,+ updated_at: job.updated_at,+ },+ )+ .await+ .map_err(|error| report!(errors::StorageError::from(error)))+ }+#[instrument(skip_all)]async fn count_batch_blocklist_jobs_by_merchant_id(&self,@@ -220,6 +318,7 @@ impl BatchBlocklistJobInterface for MockDb {file_key: None,error_message: None,expires_at: None,+ metadata: new.metadata,};jobs.push(job.clone());Ok(job)@@ -303,10 +402,33 @@ impl BatchBlocklistJobInterface for MockDb {if let Some(expires_at) = update.expires_at {job.expires_at = Some(expires_at);}+ if let Some(metadata) = update.metadata {+ job.metadata = Some(metadata);+ }job.updated_at = update.updated_at;Ok(job.clone())}+ async fn update_profile_clone_job_target(+ &self,+ id: &str,+ merchant_id: &str,+ profile_id: &common_utils::id_type::ProfileId,+ update: storage::BlocklistProfileCloneTargetUpdate,+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {+ let mut jobs = self.batch_blocklist_jobs.lock().await;+ let job = jobs+ .iter_mut()+ .find(|job| job.id == id && job.merchant_id.get_string_repr() == merchant_id)+ .ok_or_else(|| {+ errors::StorageError::ValueNotFound(format!(+ "BatchBlocklistJob not found for id = {id} and merchant_id = {merchant_id}"+ ))+ })?;+ apply_profile_clone_target_update(job, profile_id, update)?;+ Ok(job.clone())+ }+#[instrument(skip_all)]async fn count_batch_blocklist_jobs_by_merchant_id(&self,@@ -377,6 +499,18 @@ impl BatchBlocklistJobInterface for KafkaStore {.await}+ async fn update_profile_clone_job_target(+ &self,+ id: &str,+ merchant_id: &str,+ 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+ }+#[instrument(skip_all)]async fn count_batch_blocklist_jobs_by_merchant_id(&self,diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rsindex af5bc66643..ca626629e0 100644--- a/crates/router/src/routes/app.rs+++ b/crates/router/src/routes/app.rs@@ -2000,6 +2000,9 @@ impl Blocklist {.service(web::resource("/export").route(web::post().to(blocklist::create_blocklist_export)),)+ .service(+ web::resource("/clone").route(web::post().to(blocklist::clone_blocklist_entries)),+ )}}diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rsindex fbbd340621..f088ff8a0a 100644--- a/crates/router/src/routes/blocklist.rs+++ b/crates/router/src/routes/blocklist.rs@@ -26,7 +26,7 @@ use crate::{),tag = "Blocklist",operation_id = "Block a Fingerprint",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn add_entry_to_blocklist(state: web::Data<AppState>,@@ -77,7 +77,7 @@ pub async fn add_entry_to_blocklist(),tag = "Blocklist",operation_id = "Unblock a Fingerprint",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn remove_entry_from_blocklist(state: web::Data<AppState>,@@ -132,7 +132,7 @@ pub async fn remove_entry_from_blocklist(),tag = "Blocklist",operation_id = "List Blocked fingerprints of a particular kind",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = []), ("publishable_key" = [])))]pub async fn list_blocked_payment_methods(state: web::Data<AppState>,@@ -203,7 +203,7 @@ pub async fn list_blocked_payment_methods(),tag = "Blocklist",operation_id = "Count blocked fingerprints of a particular kind",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn get_blocklist_count(state: web::Data<AppState>,@@ -258,7 +258,7 @@ pub async fn get_blocklist_count(),tag = "Blocklist",operation_id = "Look up whether a value is blocked",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn lookup_blocklist_entry(state: web::Data<AppState>,@@ -309,7 +309,7 @@ pub async fn lookup_blocklist_entry(),tag = "Blocklist",operation_id = "Toggle blocklist guard for a particular merchant",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn toggle_blocklist_guard(state: web::Data<AppState>,@@ -375,7 +375,7 @@ pub struct BatchBlocklistUploadForm {),tag = "Blocklist",operation_id = "Upload a batch blocklist CSV",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn upload_batch_blocklist(state: web::Data<AppState>,@@ -435,7 +435,7 @@ pub async fn upload_batch_blocklist(),tag = "Blocklist",operation_id = "Get batch blocklist job status",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn get_batch_blocklist_job_status(state: web::Data<AppState>,@@ -477,7 +477,7 @@ pub async fn get_batch_blocklist_job_status(("limit" = Option<u32>, Query, description = "Maximum number of jobs to return (default 10)"),("offset" = Option<u32>, Query, description = "Zero-based offset for pagination (default 0)"),("job_type" = Option<BatchBlocklistJobType>, Query, description = "Restricts the listing to \- `upload` or `export` jobs. Both kinds are returned when omitted, newest first."),+ `upload`, `export`, or `profile_clone` jobs. All kinds are returned when omitted"),("X-Profile-Id" = Option<String>, Header, description = "Restricts the listing to jobs run \for this business profile, plus jobs that predate profile scoping. When no profile can be \resolved, all of the merchant's jobs are returned, as before."),@@ -487,7 +487,7 @@ pub async fn get_batch_blocklist_job_status(),tag = "Blocklist",operation_id = "List batch blocklist jobs",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn list_batch_blocklist_jobs(state: web::Data<AppState>,@@ -536,7 +536,7 @@ pub async fn list_batch_blocklist_jobs(),tag = "Blocklist",operation_id = "Start a blocklist CSV export",- security(("api_key" = []))+ security(("api_key" = []), ("jwt_key" = [])))]pub async fn create_blocklist_export(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {let flow = Flow::CreateBlocklistExport;@@ -565,3 +565,51 @@ pub async fn create_blocklist_export(state: web::Data<AppState>, req: HttpReques)).await}++#[utoipa::path(+ post,+ path = "/blocklist/clone",+ request_body = CloneBlocklistEntriesRequest,+ params(+ ("X-Profile-Id" = Option<String>, Header, description = "Source profile whose entries are copied; it also owns the clone job. Required when the authenticated dashboard session does not provide a profile context")+ ),+ responses(+ (status = 200, description = "One background job was started; it clones onto the target profiles one at a time", body = CloneBlocklistEntriesResponse),+ (status = 400, description = "Missing profile context, no targets given, or a target is the source profile"),+ (status = 404, description = "The source or a target profile does not belong to the merchant")+ ),+ tag = "Blocklist",+ operation_id = "Clone blocklist entries across profiles",+ security(("api_key" = []), ("jwt_key" = []))+)]+pub async fn clone_blocklist_entries(+ state: web::Data<AppState>,+ req: HttpRequest,+ json_payload: web::Json<api_blocklist::CloneBlocklistEntriesRequest>,+) -> HttpResponse {+ let flow = Flow::CloneBlocklistEntries;+ Box::pin(api::server_wrap(+ flow,+ state,+ &req,+ json_payload.into_inner(),+ |state, auth: auth::AuthenticationData, body, _| {+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());+ blocklist::clone_blocklist_entries(state, auth.platform, profile_id, body)+ },+ auth::auth_type(+ &auth::HeaderAuth(auth::ApiKeyAuth {+ allow_connected_scope_operation: true,+ allow_platform_self_operation: false,+ }),+ &auth::JWTAuth {+ permission: Permission::MerchantAccountWrite,+ allow_connected: true,+ allow_platform: false,+ },+ req.headers(),+ ),+ api_locking::LockAction::NotApplicable,+ ))+ .await+}diff --git a/crates/router/src/routes/lock_utils.rs b/crates/router/src/routes/lock_utils.rsindex e3f9683427..c7ced9669a 100644--- a/crates/router/src/routes/lock_utils.rs+++ b/crates/router/src/routes/lock_utils.rs@@ -120,6 +120,7 @@ impl From<Flow> for ApiIdentifier {Flow::GetBlocklistCount => Self::Blocklist,Flow::LookupBlocklistEntry => Self::Blocklist,Flow::CreateBlocklistExport => Self::Blocklist,+ Flow::CloneBlocklistEntries => Self::Blocklist,Flow::MerchantConnectorsCreate| Flow::MerchantConnectorsRetrieve| Flow::MerchantConnectorsUpdatediff --git a/crates/router/src/types/storage/batch_blocklist_job.rs b/crates/router/src/types/storage/batch_blocklist_job.rsindex 4ad95068ff..03fe86032f 100644--- a/crates/router/src/types/storage/batch_blocklist_job.rs+++ b/crates/router/src/types/storage/batch_blocklist_job.rs@@ -25,3 +25,96 @@ pub struct BlocklistExportTrackingData {/// Written once the multipart upload starts, so a retry can discard the abandoned parts.pub upload_id: Option<String>,}++#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]+pub struct BlocklistProfileCloneTrackingData {+ pub job_id: String,+ pub merchant_id: id_type::MerchantId,+ pub processor_merchant_id: Option<id_type::MerchantId>,+ pub source_profile_id: id_type::ProfileId,+ /// Copied in this order.+ pub target_profile_ids: Vec<id_type::ProfileId>,+ /// Index into `target_profile_ids` of the target being copied; earlier ones are settled.+ pub current_target: usize,+ /// Bounds the scan, so a run spanning minutes still copies one moment of the source.+ pub snapshot_at: time::PrimitiveDateTime,+ /// The source is drained in two passes, the same split the export uses: rows carrying a+ /// `processor_merchant_id` first, then the legacy rows without one.+ pub draining_legacy_rows: bool,+ /// Keyset cursor within the current pass. `""` starts the pass from the beginning.+ pub last_fingerprint_id: String,+ /// Source rows fully handled by this target tracker. This advances with the cursor.+ pub processed_rows: i32,+}++#[derive(Debug, Clone)]+pub struct BlocklistProfileCloneTargetUpdate {+ pub status: common_enums::BatchBlocklistJobStatus,+ pub processed_rows: i32,+ pub error_message: Option<String>,+}++/// Job-level progress for a multi-target profile clone, one entry per target. The generic row+/// counters on the job stay at zero.+#[derive(Debug, Clone)]+pub struct BlocklistProfileCloneJobMetadata {+ pub targets: Vec<BlocklistProfileCloneTargetMetadata>,+}++#[derive(Debug, Clone)]+pub struct BlocklistProfileCloneTargetMetadata {+ pub profile_id: id_type::ProfileId,+ pub status: common_enums::BatchBlocklistJobStatus,+ pub processed_rows: i32,+ pub error_message: Option<String>,+}++impl From<diesel_models::batch_blocklist_job::BlocklistProfileCloneJobMetadata>+ for BlocklistProfileCloneJobMetadata+{+ fn from(+ metadata: diesel_models::batch_blocklist_job::BlocklistProfileCloneJobMetadata,+ ) -> Self {+ Self {+ targets: metadata.targets.into_iter().map(Into::into).collect(),+ }+ }+}++impl From<BlocklistProfileCloneJobMetadata>+ for diesel_models::batch_blocklist_job::BlocklistProfileCloneJobMetadata+{+ fn from(metadata: BlocklistProfileCloneJobMetadata) -> Self {+ Self {+ targets: metadata.targets.into_iter().map(Into::into).collect(),+ }+ }+}++impl From<diesel_models::batch_blocklist_job::BlocklistProfileCloneTargetMetadata>+ for BlocklistProfileCloneTargetMetadata+{+ fn from(+ target: diesel_models::batch_blocklist_job::BlocklistProfileCloneTargetMetadata,+ ) -> Self {+ Self {+ profile_id: target.profile_id,+ status: target.status,+ processed_rows: target.processed_rows,+ error_message: target.error_message,+ }+ }+}++impl From<BlocklistProfileCloneTargetMetadata>+ for diesel_models::batch_blocklist_job::BlocklistProfileCloneTargetMetadata+{+ fn from(target: BlocklistProfileCloneTargetMetadata) -> Self {+ Self {+ profile_id: target.profile_id,+ status: target.status,+ processed_rows: target.processed_rows,+ error_message: target.error_message,+ }+ }+}diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rsindex e1d2981d75..b5978e0a47 100644--- a/crates/router/src/workflows.rs+++ b/crates/router/src/workflows.rs@@ -34,3 +34,6 @@ pub mod offer_engine_notify;#[cfg(feature = "v1")]pub mod blocklist_export;++#[cfg(feature = "v1")]+pub mod blocklist_profile_clone;diff --git a/crates/router/src/workflows/batch_blocklist_upload.rs b/crates/router/src/workflows/batch_blocklist_upload.rsindex 5387201fc5..4c7723ad15 100644--- a/crates/router/src/workflows/batch_blocklist_upload.rs+++ b/crates/router/src/workflows/batch_blocklist_upload.rs@@ -104,6 +104,7 @@ async fn run_batch_job(file_key: None,error_message: None,expires_at: None,+ metadata: None,updated_at: common_utils::date_time::now(),},)@@ -186,6 +187,7 @@ impl ProcessTrackerWorkflow<SessionState> for BatchBlocklistUploadWorkflow {file_key: None,error_message: None,expires_at: None,+ metadata: None,updated_at: common_utils::date_time::now(),},)@@ -209,6 +211,7 @@ impl ProcessTrackerWorkflow<SessionState> for BatchBlocklistUploadWorkflow {file_key: None,error_message: None,expires_at: None,+ metadata: None,updated_at: common_utils::date_time::now(),},)@@ -275,6 +278,7 @@ impl ProcessTrackerWorkflow<SessionState> for BatchBlocklistUploadWorkflow {file_key: None,error_message: None,expires_at: None,+ metadata: None,updated_at: common_utils::date_time::now(),},)diff --git a/crates/router/src/workflows/blocklist_export.rs b/crates/router/src/workflows/blocklist_export.rsindex 867aba38c3..80babbabe0 100644--- a/crates/router/src/workflows/blocklist_export.rs+++ b/crates/router/src/workflows/blocklist_export.rs@@ -313,6 +313,7 @@ impl ProcessTrackerWorkflow<SessionState> for BlocklistExportWorkflow {file_key: None,error_message: None,expires_at: None,+ metadata: None,updated_at: common_utils::date_time::now(),},)@@ -341,6 +342,7 @@ impl ProcessTrackerWorkflow<SessionState> for BlocklistExportWorkflow {)),error_message: None,expires_at: parse_expiry_date(expiration),+ metadata: None,updated_at: common_utils::date_time::now(),},)@@ -401,6 +403,7 @@ impl ProcessTrackerWorkflow<SessionState> for BlocklistExportWorkflow {.to_string(),),expires_at: None,+ metadata: None,updated_at: common_utils::date_time::now(),},)diff --git a/crates/router/src/workflows/blocklist_profile_clone.rs b/crates/router/src/workflows/blocklist_profile_clone.rsnew file mode 100644index 0000000000..7edf282b2f--- /dev/null+++ b/crates/router/src/workflows/blocklist_profile_clone.rs@@ -0,0 +1,456 @@+use common_utils::{ext_traits::ValueExt, id_type};+use error_stack::ResultExt;+use router_env::{instrument, tracing};+use scheduler::{+ consumer::types::process_data, utils as pt_utils, workflows::ProcessTrackerWorkflow,+};++use crate::{+ core::{+ blocklist::clone,+ errors::{self, RouterResult},+ },+ logger::{error, info},+ routes::SessionState,+ types::storage,+};++pub struct BlocklistProfileCloneWorkflow;++/// Copies the source profile onto one target profile a page at a time.+async fn run_clone_job(+ state: &SessionState,+ process_id: &str,+ tracking_data: &mut storage::BlocklistProfileCloneTrackingData,+ merchant_id_obj: &id_type::MerchantId,+ target_profile_id: &id_type::ProfileId,+) -> RouterResult<i32> {+ let db = &*state.store;+ let job_id = tracking_data.job_id.clone();+ let merchant_id_str = merchant_id_obj.get_string_repr();++ loop {+ let page = match tracking_data.draining_legacy_rows {+ false => {+ db.list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(+ merchant_id_obj,+ &tracking_data.source_profile_id,+ tracking_data.last_fingerprint_id.clone(),+ tracking_data.snapshot_at,+ clone::CLONE_PAGE_SIZE,+ )+ .await+ }+ true => {+ db.list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(+ merchant_id_obj,+ &tracking_data.source_profile_id,+ tracking_data.last_fingerprint_id.clone(),+ tracking_data.snapshot_at,+ clone::CLONE_PAGE_SIZE,+ )+ .await+ }+ }+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| format!("Failed to read a source page for clone job {job_id}"))?;++ match page.last().map(|entry| entry.fingerprint_id.clone()) {+ // End of a pass: switch to the legacy rows, or stop if that pass is already done.+ None => match tracking_data.draining_legacy_rows {+ true => break,+ false => {+ tracking_data.draining_legacy_rows = true;+ tracking_data.last_fingerprint_id = String::new();+ persist_cursor(state, process_id, tracking_data).await?;+ }+ },+ Some(cursor) => {+ let page_len = page.len();+ let now = common_utils::date_time::now();+ let entries = page+ .into_iter()+ .map(|entry| clone::to_target_entry(entry, target_profile_id, now))+ .collect::<Vec<_>>();++ let inserted = db+ .bulk_insert_blocklist_entries(entries)+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!("Failed to insert cloned entries for job {job_id}")+ })?;++ let page_rows = i32::try_from(page_len)+ .change_context(errors::ApiErrorResponse::InternalServerError)?;+ tracking_data.processed_rows = tracking_data+ .processed_rows+ .checked_add(page_rows)+ .ok_or(errors::ApiErrorResponse::InternalServerError)?;++ tracking_data.last_fingerprint_id = cursor;+ persist_cursor(state, process_id, tracking_data).await?;++ db.update_profile_clone_job_target(+ &job_id,+ merchant_id_str,+ target_profile_id,+ storage::BlocklistProfileCloneTargetUpdate {+ status: common_enums::BatchBlocklistJobStatus::Processing,+ processed_rows: tracking_data.processed_rows,+ error_message: None,+ },+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable_lazy(|| {+ format!("Failed to update target progress for clone job {job_id}")+ })?;++ info!(+ job_id = %job_id,+ target_profile_id = ?target_profile_id,+ page_len,+ inserted,+ processed_rows = tracking_data.processed_rows,+ legacy_pass = tracking_data.draining_legacy_rows,+ "Copied a page of blocklist entries onto the target profile"+ );+ }+ }+ }++ Ok(tracking_data.processed_rows)+}++/// Rewrites the process's tracking data so a retry picks up where this run left off.+async fn persist_cursor(+ state: &SessionState,+ process_id: &str,+ tracking_data: &storage::BlocklistProfileCloneTrackingData,+) -> RouterResult<()> {+ let td_value = serde_json::to_value(tracking_data)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialise updated tracking_data")?;++ state+ .store+ .as_scheduler()+ .process_tracker_update_process_status_by_ids(+ vec![process_id.to_owned()],+ storage::ProcessTrackerUpdate::Update {+ name: None,+ retry_count: None,+ schedule_time: None,+ tracking_data: Some(td_value),+ business_status: None,+ status: None,+ updated_at: Some(common_utils::date_time::now()),+ },+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to advance the cursor for a blocklist clone job")?;++ Ok(())+}++/// Returns the delay for another copy attempt, or None once copy retries are exhausted.+fn copy_retry_delay(retry_count: i32) -> Option<i32> {+ let mapping = process_data::RetryMapping::default();+ if retry_count == 0 {+ Some(mapping.start_after)+ } else {+ pt_utils::get_delay(retry_count.saturating_add(1), &mapping.frequencies)+ }+}++/// Copies the current target and records it as completed in the job's metadata.+async fn settle_current_target(+ state: &SessionState,+ process_id: &str,+ tracking_data: &mut storage::BlocklistProfileCloneTrackingData,+ merchant_id: &id_type::MerchantId,+ target_profile_id: &id_type::ProfileId,+) -> RouterResult<()> {+ let db = &*state.store;++ run_clone_job(+ state,+ process_id,+ tracking_data,+ merchant_id,+ target_profile_id,+ )+ .await?;++ db.update_profile_clone_job_target(+ &tracking_data.job_id,+ merchant_id.get_string_repr(),+ target_profile_id,+ storage::BlocklistProfileCloneTargetUpdate {+ status: common_enums::BatchBlocklistJobStatus::Completed,+ processed_rows: tracking_data.processed_rows,+ error_message: None,+ },+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to record a clone target as completed")?;++ info!(+ job_id = %tracking_data.job_id,+ target_profile_id = ?target_profile_id,+ "Blocklist profile clone target completed"+ );+ Ok(())+}++/// Points the tracking data at the next target with a fresh cursor, returning whether one remains.+fn move_to_next_target(tracking_data: &mut storage::BlocklistProfileCloneTrackingData) -> bool {+ tracking_data.current_target = tracking_data.current_target.saturating_add(1);+ tracking_data.draining_legacy_rows = false;+ tracking_data.last_fingerprint_id = String::new();+ tracking_data.processed_rows = 0;+ tracking_data.current_target < tracking_data.target_profile_ids.len()+}++/// Requeues the tracker for the next target with a fresh copy-retry budget.+async fn requeue_for_next_target(+ state: &SessionState,+ process_id: &str,+ tracking_data: &storage::BlocklistProfileCloneTrackingData,+) -> RouterResult<()> {+ let td_value = serde_json::to_value(tracking_data)+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to serialise updated tracking_data")?;+ let now = common_utils::date_time::now();++ state+ .store+ .as_scheduler()+ .process_tracker_update_process_status_by_ids(+ vec![process_id.to_owned()],+ storage::ProcessTrackerUpdate::Update {+ name: None,+ retry_count: Some(0),+ schedule_time: Some(now),+ tracking_data: Some(td_value),+ business_status: None,+ status: Some(common_enums::ProcessTrackerStatus::New),+ updated_at: Some(now),+ },+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to requeue the blocklist clone job for its next target")?;++ Ok(())+}++const CLONE_FAILED_MESSAGE: &str = "Clone failed after repeated attempts. Please retry.";++/// Records the current target as failed once its copy retries are spent and requeues the tracker+/// for the next target. Returns whether it was requeued; `false` means no target remains.+async fn fail_current_target(+ state: &SessionState,+ process: &storage::ProcessTracker,+) -> RouterResult<bool> {+ let mut tracking_data: storage::BlocklistProfileCloneTrackingData = process+ .tracking_data+ .clone()+ .parse_value("BlocklistProfileCloneTrackingData")+ .change_context(errors::ApiErrorResponse::InternalServerError)?;+ let merchant_id = tracking_data+ .processor_merchant_id+ .clone()+ .unwrap_or_else(|| tracking_data.merchant_id.clone());+ let target_profile_id = tracking_data+ .target_profile_ids+ .get(tracking_data.current_target)+ .cloned()+ .ok_or(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Blocklist clone tracker points past its last target")?;++ state+ .store+ .update_profile_clone_job_target(+ &tracking_data.job_id,+ merchant_id.get_string_repr(),+ &target_profile_id,+ storage::BlocklistProfileCloneTargetUpdate {+ status: common_enums::BatchBlocklistJobStatus::Failed,+ processed_rows: tracking_data.processed_rows,+ error_message: Some(CLONE_FAILED_MESSAGE.to_string()),+ },+ )+ .await+ .change_context(errors::ApiErrorResponse::InternalServerError)+ .attach_printable("Failed to record a clone target as failed")?;++ match move_to_next_target(&mut tracking_data) {+ true => requeue_for_next_target(state, &process.id, &tracking_data)+ .await+ .map(|()| true),+ false => Ok(false),+ }+}++/// Marks the whole job failed without reading its metadata, so a job whose metadata is missing or+/// malformed still settles. Best effort: the caller finishes the tracker either way.+async fn fail_job(state: &SessionState, process: &storage::ProcessTracker) {+ let parsed: Result<storage::BlocklistProfileCloneTrackingData, _> = process+ .tracking_data+ .clone()+ .parse_value("BlocklistProfileCloneTrackingData");++ match parsed {+ Ok(tracking_data) => {+ let merchant_id = tracking_data+ .processor_merchant_id+ .clone()+ .unwrap_or_else(|| tracking_data.merchant_id.clone());+ state+ .store+ .update_batch_blocklist_job_by_id_merchant_id(+ &tracking_data.job_id,+ merchant_id.get_string_repr(),+ storage::BatchBlocklistJobUpdate {+ status: Some(common_enums::BatchBlocklistJobStatus::Failed),+ succeeded_rows: None,+ failed_rows: None,+ total_rows: None,+ file_key: None,+ error_message: Some(CLONE_FAILED_MESSAGE.to_string()),+ expires_at: None,+ metadata: None,+ updated_at: common_utils::date_time::now(),+ },+ )+ .await+ .inspect_err(|error| {+ error!(+ ?error,+ job_id = %tracking_data.job_id,+ "Failed to mark the blocklist clone job as failed"+ )+ })+ .ok();+ }+ Err(error) => error!(+ ?error,+ process_id = %process.id,+ "Unreadable blocklist clone tracking data; the job cannot be marked failed"+ ),+ }+}++#[async_trait::async_trait]+impl ProcessTrackerWorkflow<SessionState> for BlocklistProfileCloneWorkflow {+ /// Settles one target per run. Between targets the tracker is requeued with its retry count+ /// reset, so every target gets its own copy-retry budget; after the last one it finishes.+ #[instrument(skip_all, fields(flow = ?router_env::Flow::CloneBlocklistEntries))]+ async fn execute_workflow<'a>(+ &'a self,+ state: &'a SessionState,+ process: storage::ProcessTracker,+ ) -> Result<(), errors::ProcessTrackerError> {+ let mut tracking_data: storage::BlocklistProfileCloneTrackingData = process+ .tracking_data+ .clone()+ .parse_value("BlocklistProfileCloneTrackingData")+ .map_err(errors::ProcessTrackerError::from)?;+ let merchant_id = tracking_data+ .processor_merchant_id+ .clone()+ .unwrap_or_else(|| tracking_data.merchant_id.clone());+ let target_profile_id = tracking_data+ .target_profile_ids+ .get(tracking_data.current_target)+ .cloned()+ .ok_or(errors::ProcessTrackerError::UnexpectedFlow)?;++ settle_current_target(+ state,+ &process.id,+ &mut tracking_data,+ &merchant_id,+ &target_profile_id,+ )+ .await+ .map_err(errors::ProcessTrackerError::from)?;++ match move_to_next_target(&mut tracking_data) {+ true => requeue_for_next_target(state, &process.id, &tracking_data)+ .await+ .map_err(errors::ProcessTrackerError::from),+ false => {+ state+ .store+ .as_scheduler()+ .finish_process_with_business_status(process, "COMPLETED_BY_PT")+ .await+ .map_err(errors::ProcessTrackerError::from)?;+ info!(+ job_id = %tracking_data.job_id,+ "Blocklist profile clone job finished"+ );+ Ok(())+ }+ }+ }++ /// Retries the current target on the copy-retry schedule. Once that is spent, the target is+ /// recorded as failed and the tracker moves on to the next one. If even that fails (unreadable+ /// tracking data, or a missing or malformed job), the job is marked failed as a whole and the+ /// tracker finished, so every job reaches a final status.+ async fn error_handler<'a>(+ &'a self,+ state: &'a SessionState,+ process: storage::ProcessTracker,+ error: errors::ProcessTrackerError,+ ) -> errors::CustomResult<(), errors::ProcessTrackerError> {+ error!(+ process_id = %process.id,+ retry_count = process.retry_count,+ ?error,+ "Blocklist clone attempt failed"+ );++ match copy_retry_delay(process.retry_count) {+ Some(delay) => {+ let schedule_time = common_utils::date_time::now()+ .saturating_add(time::Duration::seconds(i64::from(delay)));+ state+ .store+ .as_scheduler()+ .retry_process(process, schedule_time)+ .await+ .change_context(errors::ProcessTrackerError::ProcessUpdateFailed)+ }+ None => match fail_current_target(state, &process).await {+ Ok(true) => Ok(()),+ Ok(false) => state+ .store+ .as_scheduler()+ .finish_process_with_business_status(process, "COMPLETED_BY_PT")+ .await+ .change_context(errors::ProcessTrackerError::ProcessUpdateFailed),+ Err(error) => {+ error!(+ ?error,+ process_id = %process.id,+ "Could not record the failed clone target; failing the whole job"+ );+ fail_job(state, &process).await;+ state+ .store+ .as_scheduler()+ .finish_process_with_business_status(process, "RETRIES_EXCEEDED")+ .await+ .change_context(errors::ProcessTrackerError::ProcessUpdateFailed)+ }+ },+ }+ }+}diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rsindex 30805a1f94..ce10484817 100644--- a/crates/router_env/src/logger/types.rs+++ b/crates/router_env/src/logger/types.rs@@ -361,6 +361,8 @@ pub enum Flow {LookupBlocklistEntry,/// Start a CSV export of the blocklistCreateBlocklistExport,+ /// Clone a profile's blocklist entries onto other profiles+ CloneBlocklistEntries,/// Incoming Webhook ReceiveIncomingWebhookReceive,/// Recovery incoming webhook receivediff --git a/migrations/2026-09-14-100000_add_metadata_to_batch_blocklist_jobs/down.sql b/migrations/2026-09-14-100000_add_metadata_to_batch_blocklist_jobs/down.sqlnew file mode 100644index 0000000000..d1124db4f2--- /dev/null+++ b/migrations/2026-09-14-100000_add_metadata_to_batch_blocklist_jobs/down.sql@@ -0,0 +1,2 @@+ALTER TABLE batch_blocklist_jobs+DROP COLUMN IF EXISTS metadata;diff --git a/migrations/2026-09-14-100000_add_metadata_to_batch_blocklist_jobs/up.sql b/migrations/2026-09-14-100000_add_metadata_to_batch_blocklist_jobs/up.sqlnew file mode 100644index 0000000000..f6f711a900--- /dev/null+++ b/migrations/2026-09-14-100000_add_metadata_to_batch_blocklist_jobs/up.sql@@ -0,0 +1,2 @@+ALTER TABLE batch_blocklist_jobs+ADD COLUMN IF NOT EXISTS metadata JSONB;