Skip to content

Open source, composable payments platform | PCI compliant | SaaS and Self-host options | Enables connectivity to multiple payment, payout, fraud, vault and tokenization providers | Uplifts authorization with intelligent routing and revenue recovery | Reduce payment processing costs with cost observability | Reduces payment ops with reconciliation

feat(blocklist): add batch blocklist CSV upload with async processing (#12149)

Ayush Anandde54c8108c0e
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index 3c899dda6c..049f9e76a4 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -5898,6 +5898,133 @@
]
}
},
+ "/blocklist/batch": {
+ "post": {
+ "tags": [
+ "Blocklist"
+ ],
+ "operationId": "Upload a batch blocklist CSV",
+ "requestBody": {
+ "description": "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MB). The CSV must have a header row: `type,data,metadata`. `type`: one of `card_bin` (6 digits), `extended_card_bin` (8 digits), `fingerprint`. `metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). Maximum 100,000 data rows.",
+ "content": {
+ "multipart/form-data": {
+ "schema": {
+ "type": "string"
+ }
+ }
+ },
+ "required": true
+ },
+ "responses": {
+ "202": {
+ "description": "Batch blocklist job initiated",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BatchBlocklistUploadResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "CSV validation error or file exceeds 5 MB limit"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ },
+ "get": {
+ "tags": [
+ "Blocklist"
+ ],
+ "operationId": "List batch blocklist jobs",
+ "parameters": [
+ {
+ "name": "limit",
+ "in": "query",
+ "description": "Maximum number of jobs to return (default 10, max 100)",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int32",
+ "nullable": true,
+ "minimum": 0
+ }
+ },
+ {
+ "name": "offset",
+ "in": "query",
+ "description": "Zero-based offset for pagination (default 0)",
+ "required": false,
+ "schema": {
+ "type": "integer",
+ "format": "int32",
+ "nullable": true,
+ "minimum": 0
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "List of batch blocklist jobs",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/ListBatchBlocklistJobsResponse"
+ }
+ }
+ }
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
+ "/blocklist/batch/{job_id}": {
+ "get": {
+ "tags": [
+ "Blocklist"
+ ],
+ "operationId": "Get batch blocklist job status",
+ "parameters": [
+ {
+ "name": "job_id",
+ "in": "path",
+ "description": "The job ID returned by the batch upload endpoint",
+ "required": true,
+ "schema": {
+ "type": "string"
+ }
+ }
+ ],
+ "responses": {
+ "200": {
+ "description": "Batch blocklist job status",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BatchBlocklistJobStatusResponse"
+ }
+ }
+ }
+ },
+ "404": {
+ "description": "Job not found"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/payouts/create": {
"post": {
"tags": [
@@ -13503,6 +13630,85 @@
"savings"
]
},
+ "BatchBlocklistJobStatus": {
+ "type": "string",
+ "enum": [
+ "initiated",
+ "processing",
+ "completed",
+ "failed"
+ ]
+ },
+ "BatchBlocklistJobStatusResponse": {
+ "type": "object",
+ "description": "Response for `GET /blocklist/batch/{job_id}`.",
+ "required": [
+ "job_id",
+ "merchant_id",
+ "status",
+ "total_rows",
+ "succeeded_rows",
+ "failed_rows",
+ "created_at",
+ "updated_at"
+ ],
+ "properties": {
+ "job_id": {
+ "type": "string"
+ },
+ "merchant_id": {
+ "type": "string"
+ },
+ "status": {
+ "$ref": "#/components/schemas/BatchBlocklistJobStatus"
+ },
+ "total_rows": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ },
+ "succeeded_rows": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ },
+ "failed_rows": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ },
+ "created_at": {
+ "type": "string",
+ "format": "date-time"
+ },
+ "updated_at": {
+ "type": "string",
+ "format": "date-time"
+ }
+ }
+ },
+ "BatchBlocklistUploadResponse": {
+ "type": "object",
+ "description": "Response returned on a successful `POST /blocklist/batch`.",
+ "required": [
+ "job_id",
+ "total_rows",
+ "status"
+ ],
+ "properties": {
+ "job_id": {
+ "type": "string"
+ },
+ "total_rows": {
+ "type": "integer",
+ "format": "int32",
+ "minimum": 0
+ },
+ "status": {
+ "$ref": "#/components/schemas/BatchBlocklistJobStatus"
+ }
+ }
+ },
"BecsBankDebitAdditionalData": {
"type": "object",
"required": [
@@ -13699,6 +13905,32 @@
}
}
},
+ "BlocklistRowError": {
+ "type": "object",
+ "description": "A single validation error found in a batch-upload CSV row.",
+ "required": [
+ "row_index",
+ "data_kind",
+ "data",
+ "reason"
+ ],
+ "properties": {
+ "row_index": {
+ "type": "integer",
+ "description": "0-based row index in the CSV (excluding header).",
+ "minimum": 0
+ },
+ "data_kind": {
+ "$ref": "#/components/schemas/BlocklistDataKind"
+ },
+ "data": {
+ "type": "string"
+ },
+ "reason": {
+ "type": "string"
+ }
+ }
+ },
"BoletoAdditionalDetails": {
"type": "object",
"properties": {
@@ -22877,6 +23109,31 @@
}
]
},
+ "ListBatchBlocklistJobsResponse": {
+ "type": "object",
+ "description": "Response for `GET /blocklist/batch`.",
+ "required": [
+ "count",
+ "total_count",
+ "data"
+ ],
+ "properties": {
+ "count": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "total_count": {
+ "type": "integer",
+ "minimum": 0
+ },
+ "data": {
+ "type": "array",
+ "items": {
+ "$ref": "#/components/schemas/BatchBlocklistJobStatusResponse"
+ }
+ }
+ }
+ },
"ListBlocklistQuery": {
"type": "object",
"required": [
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs
index 04cab94106..75bb5bb36a 100644
--- a/crates/api_models/src/blocklist.rs
+++ b/crates/api_models/src/blocklist.rs
@@ -3,6 +3,9 @@ use common_utils::events::ApiEventMetric;
use hyperswitch_masking::StrongSecret;
use utoipa::ToSchema;
+const MAX_BATCH_LIST_LIMIT: u8 = 100;
+const DEFAULT_BATCH_LIST_LIMIT: u8 = 10;
+
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(rename_all = "snake_case", tag = "type", content = "data")]
pub enum BlocklistRequest {
@@ -85,3 +88,107 @@ impl ApiEventMetric for GenerateFingerprintRequest {}
impl ApiEventMetric for ToggleBlocklistQuery {}
impl ApiEventMetric for GenerateFingerprintResponsePayload {}
impl ApiEventMetric for Card {}
+
+// ---- Batch Blocklist Upload types ----
+
+/// A single validation error found in a batch-upload CSV row.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BlocklistRowError {
+ /// 0-based row index in the CSV (excluding header).
+ pub row_index: usize,
+ #[schema(value_type = BlocklistDataKind)]
+ pub data_kind: enums::BlocklistDataKind,
+ pub data: String,
+ pub reason: String,
+}
+
+/// Response returned on a successful `POST /blocklist/batch`.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BatchBlocklistUploadResponse {
+ pub job_id: String,
+ pub total_rows: u32,
+ #[schema(value_type = BatchBlocklistJobStatus)]
+ pub status: enums::BatchBlocklistJobStatus,
+}
+
+/// Response for `GET /blocklist/batch/{job_id}`.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BatchBlocklistJobStatusResponse {
+ pub job_id: String,
+ pub merchant_id: String,
+ #[schema(value_type = BatchBlocklistJobStatus)]
+ pub status: enums::BatchBlocklistJobStatus,
+ pub total_rows: u32,
+ pub succeeded_rows: u32,
+ pub failed_rows: u32,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub created_at: time::PrimitiveDateTime,
+ #[serde(with = "common_utils::custom_serde::iso8601")]
+ pub updated_at: time::PrimitiveDateTime,
+}
+
+/// Page size for listing batch blocklist jobs. Defaults to 10, capped at 100.
+#[derive(Debug, Clone, serde::Serialize, ToSchema)]
+pub struct BatchListLimit(u8);
+
+impl BatchListLimit {
+ pub fn get(&self) -> u8 {
+ self.0
+ }
+}
+
+impl Default for BatchListLimit {
+ fn default() -> Self {
+ Self(DEFAULT_BATCH_LIST_LIMIT)
+ }
+}
+
+impl<'de> serde::Deserialize<'de> for BatchListLimit {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ let val = u8::deserialize(deserializer)?;
+ if val > MAX_BATCH_LIST_LIMIT {
+ return Err(serde::de::Error::custom(format!(
+ "limit must not exceed {MAX_BATCH_LIST_LIMIT}"
+ )));
+ }
+ Ok(Self(val))
+ }
+}
+
+/// Page offset for listing batch blocklist jobs. Defaults to 0.
+#[derive(Debug, Clone, Default, serde::Serialize, ToSchema)]
+pub struct BatchListOffset(u32);
+
+impl BatchListOffset {
+ pub fn get(&self) -> u32 {
+ self.0
+ }
+}
+
+impl<'de> serde::Deserialize<'de> for BatchListOffset {
+ fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
+ Ok(Self(u32::deserialize(deserializer)?))
+ }
+}
+
+/// Query parameters for listing batch blocklist jobs.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct ListBatchBlocklistJobsQuery {
+ #[serde(default)]
+ pub limit: BatchListLimit,
+ #[serde(default)]
+ pub offset: BatchListOffset,
+}
+
+/// Response for `GET /blocklist/batch`.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct ListBatchBlocklistJobsResponse {
+ pub count: usize,
+ pub total_count: usize,
+ pub data: Vec<BatchBlocklistJobStatusResponse>,
+}
+
+impl ApiEventMetric for BatchBlocklistUploadResponse {}
+impl ApiEventMetric for BatchBlocklistJobStatusResponse {}
+impl ApiEventMetric for ListBatchBlocklistJobsQuery {}
+impl ApiEventMetric for ListBatchBlocklistJobsResponse {}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index bb57b46619..70b6bfba73 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -656,6 +656,7 @@ impl PaymentResourceUpdateStatus {
#[derive(
Clone,
+ Copy,
Debug,
PartialEq,
Eq,
@@ -10709,6 +10710,7 @@ pub enum ProcessTrackerRunner {
DisputeListWorkflow,
InvoiceSyncflow,
PayoutSyncWorkFlow,
+ BatchBlocklistUpload,
}
#[derive(
@@ -11340,3 +11342,25 @@ pub enum VaultEnv {
Sandbox,
Live,
}
+
+#[derive(
+ Clone,
+ Copy,
+ Debug,
+ Eq,
+ PartialEq,
+ serde::Deserialize,
+ serde::Serialize,
+ strum::Display,
+ strum::EnumString,
+ ToSchema,
+)]
+#[router_derive::diesel_enum(storage_type = "text")]
+#[serde(rename_all = "snake_case")]
+#[strum(serialize_all = "snake_case")]
+pub enum BatchBlocklistJobStatus {
+ Initiated,
+ Processing,
+ Completed,
+ Failed,
+}
diff --git a/crates/diesel_models/src/batch_blocklist_job.rs b/crates/diesel_models/src/batch_blocklist_job.rs
new file mode 100644
index 0000000000..86697e199d
--- /dev/null
+++ b/crates/diesel_models/src/batch_blocklist_job.rs
@@ -0,0 +1,42 @@
+use common_enums::BatchBlocklistJobStatus;
+use common_utils::id_type;
+use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
+use serde::{Deserialize, Serialize};
+use time::PrimitiveDateTime;
+
+use crate::schema::batch_blocklist_jobs;
+
+#[derive(Clone, Debug, Identifiable, Queryable, Selectable, Deserialize, Serialize)]
+#[diesel(table_name = batch_blocklist_jobs, primary_key(id), check_for_backend(diesel::pg::Pg))]
+pub struct BatchBlocklistJob {
+ pub id: String,
+ pub merchant_id: id_type::MerchantId,
+ pub status: BatchBlocklistJobStatus,
+ pub total_rows: i32,
+ pub succeeded_rows: i32,
+ pub failed_rows: i32,
+ pub created_at: PrimitiveDateTime,
+ pub updated_at: PrimitiveDateTime,
+}
+
+#[derive(Clone, Debug, Insertable, Deserialize, Serialize)]
+#[diesel(table_name = batch_blocklist_jobs)]
+pub struct BatchBlocklistJobNew {
+ pub id: String,
+ pub merchant_id: id_type::MerchantId,
+ pub status: BatchBlocklistJobStatus,
+ pub total_rows: i32,
+ pub succeeded_rows: i32,
+ pub failed_rows: i32,
+ pub created_at: PrimitiveDateTime,
+ pub updated_at: PrimitiveDateTime,
+}
+
+#[derive(Clone, Debug, AsChangeset)]
+#[diesel(table_name = batch_blocklist_jobs)]
+pub struct BatchBlocklistJobUpdate {
+ pub status: Option<BatchBlocklistJobStatus>,
+ pub succeeded_rows: Option<i32>,
+ pub failed_rows: Option<i32>,
+ pub updated_at: PrimitiveDateTime,
+}
diff --git a/crates/diesel_models/src/lib.rs b/crates/diesel_models/src/lib.rs
index c2bb2a09da..b2832099da 100644
--- a/crates/diesel_models/src/lib.rs
+++ b/crates/diesel_models/src/lib.rs
@@ -1,5 +1,6 @@
pub mod address;
pub mod api_keys;
+pub mod batch_blocklist_job;
pub mod blocklist_lookup;
pub mod business_profile;
pub mod capture;
diff --git a/crates/diesel_models/src/query.rs b/crates/diesel_models/src/query.rs
index 5f28a0019e..52c517ec4f 100644
--- a/crates/diesel_models/src/query.rs
+++ b/crates/diesel_models/src/query.rs
@@ -9,6 +9,7 @@ pub mod configs;
pub mod authentication;
pub mod authorization;
+pub mod batch_blocklist_job;
pub mod blocklist;
pub mod blocklist_fingerprint;
pub mod callback_mapper;
diff --git a/crates/diesel_models/src/query/batch_blocklist_job.rs b/crates/diesel_models/src/query/batch_blocklist_job.rs
new file mode 100644
index 0000000000..2f4a398328
--- /dev/null
+++ b/crates/diesel_models/src/query/batch_blocklist_job.rs
@@ -0,0 +1,78 @@
+use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+
+use super::generics;
+use crate::{
+ batch_blocklist_job::{BatchBlocklistJob, BatchBlocklistJobNew, BatchBlocklistJobUpdate},
+ schema::batch_blocklist_jobs::dsl,
+ PgPooledConn, StorageResult,
+};
+
+impl BatchBlocklistJobNew {
+ pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<BatchBlocklistJob> {
+ generics::generic_insert(conn, self).await
+ }
+}
+
+impl BatchBlocklistJob {
+ pub async fn find_by_id_merchant_id(
+ conn: &PgPooledConn,
+ id: &str,
+ merchant_id: &str,
+ ) -> StorageResult<Self> {
+ generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
+ conn,
+ dsl::id
+ .eq(id.to_owned())
+ .and(dsl::merchant_id.eq(merchant_id.to_owned())),
+ )
+ .await
+ }
+
+ pub async fn list_by_merchant_id(
+ conn: &PgPooledConn,
+ merchant_id: &str,
+ limit: i64,
+ offset: i64,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::merchant_id.eq(merchant_id.to_owned()),
+ Some(limit),
+ Some(offset),
+ Some(dsl::created_at.desc()),
+ )
+ .await
+ }
+
+ pub async fn count_by_merchant_id(
+ conn: &PgPooledConn,
+ merchant_id: &str,
+ ) -> StorageResult<usize> {
+ generics::generic_count::<<Self as HasTable>::Table, _>(
+ conn,
+ dsl::merchant_id.eq(merchant_id.to_owned()),
+ )
+ .await
+ }
+
+ pub async fn update_by_id_merchant_id(
+ conn: &PgPooledConn,
+ id: &str,
+ merchant_id: &str,
+ update: BatchBlocklistJobUpdate,
+ ) -> StorageResult<Self> {
+ generics::generic_update_with_unique_predicate_get_result::<
+ <Self as HasTable>::Table,
+ _,
+ _,
+ _,
+ >(
+ conn,
+ dsl::id
+ .eq(id.to_owned())
+ .and(dsl::merchant_id.eq(merchant_id.to_owned())),
+ update,
+ )
+ .await
+ }
+}
diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rs
index 051c86bc71..62c4b3d9c7 100644
--- a/crates/diesel_models/src/query/blocklist.rs
+++ b/crates/diesel_models/src/query/blocklist.rs
@@ -1,8 +1,11 @@
+use async_bb8_diesel::AsyncRunQueryDsl;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
+use error_stack::ResultExt;
use super::generics;
use crate::{
blocklist::{Blocklist, BlocklistNew},
+ errors,
schema::blocklist::dsl,
PgPooledConn, StorageResult,
};
@@ -11,6 +14,25 @@ impl BlocklistNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Blocklist> {
generics::generic_insert(conn, self).await
}
+
+ pub async fn bulk_insert_on_conflict_do_nothing(
+ conn: &PgPooledConn,
+ entries: Vec<Self>,
+ ) -> StorageResult<usize> {
+ let query = diesel::insert_into(<Blocklist as HasTable>::table())
+ .values(entries)
+ .on_conflict((dsl::merchant_id, dsl::fingerprint_id))
+ .do_nothing();
+
+ generics::db_metrics::track_database_call::<<Blocklist as HasTable>::Table, _, _>(
+ query.execute_async(conn),
+ generics::db_metrics::DatabaseOperation::Insert,
+ )
+ .await
+ .map_err(|e| error_stack::report!(e))
+ .change_context(errors::DatabaseError::Others)
+ .attach_printable("Failed to bulk insert blocklist entries")
+ }
}
impl Blocklist {
diff --git a/crates/diesel_models/src/query/utils.rs b/crates/diesel_models/src/query/utils.rs
index b33d37d157..4c26690b33 100644
--- a/crates/diesel_models/src/query/utils.rs
+++ b/crates/diesel_models/src/query/utils.rs
@@ -104,6 +104,7 @@ impl_get_primary_key!(
schema::process_tracker::table,
schema::invoice::table,
schema::subscription::table,
+ schema::batch_blocklist_jobs::table,
// v2 tables
schema_v2::dashboard_metadata::table,
schema_v2::merchant_connector_account::table,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index 37d9ae2df3..d54b816f07 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -184,6 +184,25 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ batch_blocklist_jobs (id) {
+ #[max_length = 64]
+ id -> Varchar,
+ #[max_length = 64]
+ merchant_id -> Varchar,
+ #[max_length = 32]
+ status -> Varchar,
+ total_rows -> Int4,
+ succeeded_rows -> Int4,
+ failed_rows -> Int4,
+ created_at -> Timestamp,
+ updated_at -> Timestamp,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1904,6 +1923,7 @@ diesel::allow_tables_to_appear_in_same_query!(
address,
api_keys,
authentication,
+ batch_blocklist_jobs,
blocklist,
blocklist_fingerprint,
blocklist_lookup,
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 7c4e20d0d3..d0915b4725 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -184,6 +184,25 @@ diesel::table! {
}
}
+diesel::table! {
+ use diesel::sql_types::*;
+ use crate::enums::diesel_exports::*;
+
+ batch_blocklist_jobs (id) {
+ #[max_length = 64]
+ id -> Varchar,
+ #[max_length = 64]
+ merchant_id -> Varchar,
+ #[max_length = 32]
+ status -> Varchar,
+ total_rows -> Int4,
+ succeeded_rows -> Int4,
+ failed_rows -> Int4,
+ created_at -> Timestamp,
+ updated_at -> Timestamp,
+ }
+}
+
diesel::table! {
use diesel::sql_types::*;
use crate::enums::diesel_exports::*;
@@ -1855,6 +1874,7 @@ diesel::allow_tables_to_appear_in_same_query!(
address,
api_keys,
authentication,
+ batch_blocklist_jobs,
blocklist,
blocklist_fingerprint,
blocklist_lookup,
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index d2b6ab0f2c..4208172995 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -189,6 +189,9 @@ Never share your secret api keys. Keep them guarded and secure.
routes::blocklist::list_blocked_payment_methods,
routes::blocklist::add_entry_to_blocklist,
routes::blocklist::toggle_blocklist_guard,
+ routes::blocklist::upload_batch_blocklist,
+ routes::blocklist::get_batch_blocklist_job_status,
+ routes::blocklist::list_batch_blocklist_jobs,
// Routes for payouts
routes::payouts::payouts_create,
@@ -925,6 +928,11 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::blocklist::BlocklistResponse,
api_models::blocklist::ToggleBlocklistResponse,
api_models::blocklist::ListBlocklistQuery,
+ api_models::blocklist::BatchBlocklistUploadResponse,
+ api_models::blocklist::BatchBlocklistJobStatusResponse,
+ api_models::blocklist::ListBatchBlocklistJobsResponse,
+ api_models::blocklist::BlocklistRowError,
+ api_models::enums::BatchBlocklistJobStatus,
api_models::enums::BlocklistDataKind,
api_models::enums::ErrorCategory,
api_models::webhook_events::EventListConstraints,
diff --git a/crates/openapi/src/routes/blocklist.rs b/crates/openapi/src/routes/blocklist.rs
index 741925b93d..84462416f9 100644
--- a/crates/openapi/src/routes/blocklist.rs
+++ b/crates/openapi/src/routes/blocklist.rs
@@ -57,3 +57,57 @@ pub async fn remove_entry_from_blocklist() {}
security(("api_key" = []))
)]
pub async fn list_blocked_payment_methods() {}
+
+#[utoipa::path(
+ post,
+ path = "/blocklist/batch",
+ request_body(
+ content = String,
+ content_type = "multipart/form-data",
+ description = "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MB). \
+ The CSV must have a header row: `type,data,metadata`. \
+ `type`: one of `card_bin` (6 digits), `extended_card_bin` (8 digits), `fingerprint`. \
+ `metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). \
+ Maximum 100,000 data rows.",
+ ),
+ responses(
+ (status = 202, description = "Batch blocklist job initiated", body = BatchBlocklistUploadResponse),
+ (status = 400, description = "CSV validation error or file exceeds 5 MB limit"),
+ ),
+ tag = "Blocklist",
+ operation_id = "Upload a batch blocklist CSV",
+ security(("api_key" = []))
+)]
+pub async fn upload_batch_blocklist() {}
+
+#[utoipa::path(
+ get,
+ path = "/blocklist/batch/{job_id}",
+ params(
+ ("job_id" = String, Path, description = "The job ID returned by the batch upload endpoint"),
+ ),
+ responses(
+ (status = 200, description = "Batch blocklist job status", body = BatchBlocklistJobStatusResponse),
+ (status = 404, description = "Job not found"),
+ ),
+ tag = "Blocklist",
+ operation_id = "Get batch blocklist job status",
+ security(("api_key" = []))
+)]
+pub async fn get_batch_blocklist_job_status() {}
+
+#[utoipa::path(
+ get,
+ path = "/blocklist/batch",
+ params(
+ ("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)"),
+ ),
+ responses(
+ (status = 200, description = "List of batch blocklist jobs", body = ListBatchBlocklistJobsResponse),
+ ),
+ tag = "Blocklist",
+ operation_id = "List batch blocklist jobs",
+ security(("api_key" = []))
+)]
+pub async fn list_batch_blocklist_jobs() {}
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 70d4056f03..f84de3443f 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -346,6 +346,21 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
storage::ProcessTrackerRunner::PayoutSyncWorkFlow => {
Ok(Box::new(workflows::payout_sync::PayoutSyncWorkFlow))
}
+ storage::ProcessTrackerRunner::BatchBlocklistUpload => {
+ #[cfg(feature = "v1")]
+ {
+ Ok(Box::new(
+ workflows::batch_blocklist_upload::BatchBlocklistUploadWorkflow,
+ ))
+ }
+ #[cfg(feature = "v2")]
+ {
+ Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow))
+ .attach_printable(
+ "Cannot run batch blocklist upload workflow when v1 feature is disabled",
+ )
+ }
+ }
}
};
diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rs
index 8a5b2dc1f3..67d5ef3a88 100644
--- a/crates/router/src/core/blocklist.rs
+++ b/crates/router/src/core/blocklist.rs
@@ -1,3 +1,4 @@
+pub mod batch;
pub mod transformers;
pub mod utils;
@@ -65,3 +66,45 @@ pub async fn toggle_blocklist_guard(
.await
.map(services::ApplicationResponse::Json)
}
+
+pub async fn upload_batch_blocklist(
+ state: SessionState,
+ platform: domain::Platform,
+ csv_bytes: bytes::Bytes,
+) -> RouterResponse<api_blocklist::BatchBlocklistUploadResponse> {
+ batch::initiate_batch_blocklist_upload(
+ &state,
+ platform.get_processor().get_account().get_id(),
+ csv_bytes,
+ )
+ .await
+ .map(services::ApplicationResponse::Json)
+}
+
+pub async fn get_batch_blocklist_job_status(
+ state: SessionState,
+ platform: domain::Platform,
+ job_id: String,
+) -> RouterResponse<api_blocklist::BatchBlocklistJobStatusResponse> {
+ batch::get_batch_blocklist_job_status(
+ &state,
+ platform.get_processor().get_account().get_id(),
+ &job_id,
+ )
+ .await
+ .map(services::ApplicationResponse::Json)
+}
+
+pub async fn list_batch_blocklist_jobs(
+ state: SessionState,
+ platform: domain::Platform,
+ query: api_blocklist::ListBatchBlocklistJobsQuery,
+) -> RouterResponse<api_blocklist::ListBatchBlocklistJobsResponse> {
+ batch::list_batch_blocklist_jobs(
+ &state,
+ platform.get_processor().get_account().get_id(),
+ query,
+ )
+ .await
+ .map(services::ApplicationResponse::Json)
+}
diff --git a/crates/router/src/core/blocklist/batch.rs b/crates/router/src/core/blocklist/batch.rs
new file mode 100644
index 0000000000..c56133f8de
--- /dev/null
+++ b/crates/router/src/core/blocklist/batch.rs
@@ -0,0 +1,546 @@
+//! Batch blocklist upload helpers.
+use api_models::blocklist as api_blocklist;
+use common_utils::{date_time, id_type};
+use csv::{ReaderBuilder, Trim, WriterBuilder};
+use error_stack::{report, ResultExt};
+use futures::future;
+use router_env::{instrument, tracing};
+use scheduler::utils as pt_utils;
+use serde::Deserialize;
+
+use crate::{
+ core::errors::{self, RouterResult, StorageErrorExt},
+ logger,
+ routes::SessionState,
+ types::storage,
+};
+
+const CHUNK_SIZE: usize = 2_000;
+const BATCH_BLOCKLIST_TASK: &str = "BATCH_BLOCKLIST_UPLOAD";
+const BATCH_BLOCKLIST_TAGS: [&str; 2] = ["BLOCKLIST", "BATCH"];
+const MAX_BATCH_CSV_ROWS: usize = 100_000;
+
+/// Returns the file storage key for the original uploaded CSV.
+fn original_input_key(merchant_id: &str, job_id: &str) -> String {
+ format!("blocklist/batch/{merchant_id}/{job_id}/original.csv")
+}
+
+/// Returns the file storage key for a specific input chunk of a batch job.
+pub(crate) fn input_chunk_key(merchant_id: &str, job_id: &str, chunk_idx: u32) -> String {
+ format!("blocklist/batch/{merchant_id}/{job_id}/input_chunks/{chunk_idx:03}.csv")
+}
+
+#[derive(Debug, Clone)]
+pub(crate) struct BlocklistRow {
+ pub data_kind: common_enums::BlocklistDataKind,
+ pub data: String,
+ pub metadata: Option<serde_json::Value>,
+}
+
+#[derive(Debug, Deserialize)]
+struct BlocklistCsvRecord {
+ #[serde(rename = "type")]
+ kind: String,
+ data: String,
+ #[serde(default)]
+ metadata: Option<String>,
+}
+
+fn parse_metadata(s: &str) -> Option<serde_json::Value> {
+ let map: serde_json::Map<String, serde_json::Value> = s
+ .split(';')
+ .filter_map(|pair| {
+ let mut parts = pair.splitn(2, '=');
+ let key = parts.next()?.trim().to_string();
+ let value = parts.next()?.trim().to_string();
+ if key.is_empty() {
+ return None;
+ }
+ Some((key, serde_json::Value::String(value)))
+ })
+ .collect();
+ if map.is_empty() {
+ None
+ } else {
+ Some(serde_json::Value::Object(map))
+ }
+}
+
+impl BlocklistRow {
+ fn build_row_error(
+ row_index: usize,
+ data_kind: common_enums::BlocklistDataKind,
+ data: String,
+ reason: impl Into<String>,
+ ) -> api_blocklist::BlocklistRowError {
+ api_blocklist::BlocklistRowError {
+ row_index,
+ data_kind,
+ data,
+ reason: reason.into(),
+ }
+ }
+
+ fn parse_kind(kind: &str) -> Option<common_enums::BlocklistDataKind> {
+ match kind {
+ "card_bin" => Some(common_enums::BlocklistDataKind::CardBin),
+ "extended_card_bin" => Some(common_enums::BlocklistDataKind::ExtendedCardBin),
+ "fingerprint" => Some(common_enums::BlocklistDataKind::PaymentMethod),
+ _ => None,
+ }
+ }
+
+ fn from_csv_record(
+ row_index: usize,
+ record: BlocklistCsvRecord,
+ ) -> Result<Self, api_blocklist::BlocklistRowError> {
+ let kind = record.kind.to_lowercase();
+ let data = record.data;
+
+ let parsed_kind = Self::parse_kind(&kind).ok_or_else(|| {
+ Self::build_row_error(
+ row_index,
+ common_enums::BlocklistDataKind::CardBin,
+ data.clone(),
+ format!(
+ "unknown type `{kind}`; expected card_bin, extended_card_bin, or fingerprint"
+ ),
+ )
+ })?;
+
+ if data.is_empty() {
+ return Err(Self::build_row_error(
+ row_index,
+ parsed_kind,
+ String::new(),
+ "data field must not be empty",
+ ));
+ }
+
+ let format_error = match parsed_kind {
+ common_enums::BlocklistDataKind::CardBin => {
+ if data.len() == 6 && data.chars().all(|c| c.is_ascii_digit()) {
+ None
+ } else {
+ Some("card_bin must be exactly 6 digits")
+ }
+ }
+ common_enums::BlocklistDataKind::ExtendedCardBin => {
+ if data.len() == 8 && data.chars().all(|c| c.is_ascii_digit()) {
+ None
+ } else {
+ Some("extended_card_bin must be exactly 8 digits")
+ }
+ }
+ common_enums::BlocklistDataKind::PaymentMethod => None,
+ };
+
+ if let Some(reason) = format_error {
+ return Err(Self::build_row_error(
+ row_index,
+ parsed_kind,
+ data.clone(),
+ reason,
+ ));
+ }
+
+ let metadata_raw = record.metadata.as_deref().filter(|s| !s.is_empty());
+ let metadata = match metadata_raw {
+ None => None,
+ Some(s) => match parse_metadata(s) {
+ Some(m) => Some(m),
+ None => {
+ return Err(Self::build_row_error(
+ row_index,
+ parsed_kind,
+ data.clone(),
+ "metadata must be in key=value format, separated by semicolons (e.g. reason=fraud;source=manual)",
+ ));
+ }
+ },
+ };
+
+ Ok(Self {
+ data_kind: parsed_kind,
+ data,
+ metadata,
+ })
+ }
+}
+
+/// Parses a user-uploaded CSV into blocklist rows, stopping at the first invalid row.
+fn parse_csv(csv_bytes: &[u8]) -> Result<Vec<BlocklistRow>, api_blocklist::BlocklistRowError> {
+ let mut csv_reader = ReaderBuilder::new()
+ .trim(Trim::All)
+ .flexible(true)
+ .from_reader(csv_bytes);
+
+ let mut rows = Vec::new();
+ for (row_index, result) in csv_reader
+ .deserialize::<BlocklistCsvRecord>()
+ .enumerate()
+ .take(MAX_BATCH_CSV_ROWS + 1)
+ {
+ match result {
+ Ok(record) => rows.push(BlocklistRow::from_csv_record(row_index, record)?),
+ Err(error) => {
+ return Err(BlocklistRow::build_row_error(
+ row_index,
+ common_enums::BlocklistDataKind::CardBin,
+ String::new(),
+ error.to_string(),
+ ))
+ }
+ }
+ }
+
+ Ok(rows)
+}
+
+/// Serializes a slice of blocklist rows into headerless CSV bytes for chunk storage.
+fn rows_to_csv_bytes(rows: &[BlocklistRow]) -> RouterResult<Vec<u8>> {
+ let mut writer = WriterBuilder::new()
+ .has_headers(false)
+ .from_writer(Vec::new());
+ for row in rows {
+ let metadata_str = row
+ .metadata
+ .as_ref()
+ .map(|m| {
+ if let serde_json::Value::Object(map) = m {
+ map.iter()
+ .map(|(k, v)| {
+ let val = match v {
+ serde_json::Value::String(s) => s.clone(),
+ other => other.to_string(),
+ };
+ format!("{k}={val}")
+ })
+ .collect::<Vec<_>>()
+ .join(";")
+ } else {
+ String::new()
+ }
+ })
+ .unwrap_or_default();
+ let type_str = match row.data_kind {
+ common_enums::BlocklistDataKind::CardBin => "card_bin",
+ common_enums::BlocklistDataKind::ExtendedCardBin => "extended_card_bin",
+ common_enums::BlocklistDataKind::PaymentMethod => "fingerprint",
+ };
+ writer
+ .write_record([type_str, row.data.as_str(), metadata_str.as_str()])
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialize batch blocklist input chunk row")?;
+ }
+
+ writer
+ .into_inner()
+ .map_err(|error| error.into_error())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to finalize batch blocklist input chunk CSV")
+}
+
+/// Parses a stored input chunk CSV (no header) into blocklist rows.
+pub(crate) fn parse_chunk_csv(csv_bytes: &[u8]) -> RouterResult<Vec<BlocklistRow>> {
+ let mut csv_reader = ReaderBuilder::new()
+ .has_headers(false)
+ .trim(Trim::All)
+ .from_reader(csv_bytes);
+ let mut rows = Vec::new();
+
+ for (row_index, result) in csv_reader.deserialize::<BlocklistCsvRecord>().enumerate() {
+ let record = result
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to parse batch blocklist input chunk CSV")?;
+
+ let row = BlocklistRow::from_csv_record(row_index, record).map_err(|error| {
+ report!(errors::ApiErrorResponse::InternalServerError).attach_printable(format!(
+ "Invalid batch blocklist input chunk row: {error:?}"
+ ))
+ })?;
+
+ rows.push(row);
+ }
+
+ Ok(rows)
+}
+
+/// Validates CSV size and content, returning parsed rows or an error for the first invalid row.
+fn validate_csv(csv_bytes: &[u8]) -> RouterResult<Vec<BlocklistRow>> {
+ let rows = parse_csv(csv_bytes).map_err(|row_err| {
+ logger::warn!(
+ row_index = row_err.row_index,
+ "Batch blocklist CSV validation failed"
+ );
+ let error_json = serde_json::to_string(&row_err)
+ .unwrap_or_else(|_| format!("validation error at row {}", row_err.row_index));
+ errors::ApiErrorResponse::InvalidRequestData {
+ message: error_json,
+ }
+ })?;
+
+ if rows.is_empty() {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: "CSV must contain at least one valid data row".to_string(),
+ }
+ .into());
+ }
+
+ if rows.len() > MAX_BATCH_CSV_ROWS {
+ return Err(errors::ApiErrorResponse::InvalidRequestData {
+ message: format!(
+ "CSV exceeds maximum allowed rows ({MAX_BATCH_CSV_ROWS}); got {}",
+ rows.len()
+ ),
+ }
+ .into());
+ }
+
+ Ok(rows)
+}
+
+/// Validates the CSV, splits it into chunks, uploads them to file storage, and enqueues a process tracker job.
+#[instrument(skip_all, fields(flow = ?router_env::Flow::BatchBlocklistUpload))]
+pub async fn initiate_batch_blocklist_upload(
+ state: &SessionState,
+ merchant_id: &id_type::MerchantId,
+ csv_bytes: bytes::Bytes,
+) -> RouterResult<api_blocklist::BatchBlocklistUploadResponse> {
+ let rows = validate_csv(&csv_bytes)?;
+ let total_rows = rows.len();
+ let job_id = common_utils::generate_id(crate::consts::ID_LENGTH, "blkbatch");
+ let mid_str = merchant_id.get_string_repr().to_owned();
+ let original_key = original_input_key(&mid_str, &job_id);
+ let chunks: Vec<&[BlocklistRow]> = rows.chunks(CHUNK_SIZE).collect();
+ let chunk_total_count = u32::try_from(chunks.len())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Chunk count exceeds u32::MAX")?;
+
+ logger::info!(
+ job_id = %job_id,
+ total_rows,
+ chunk_total_count,
+ "Uploading batch blocklist input files to file storage"
+ );
+
+ state
+ .file_storage_client
+ .upload_file(&original_key, csv_bytes.to_vec())
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to upload original batch blocklist CSV")?;
+
+ let upload_futures: Vec<_> = chunks
+ .iter()
+ .enumerate()
+ .map(|(idx, chunk_rows)| {
+ let chunk_idx =
+ u32::try_from(idx).change_context(errors::ApiErrorResponse::InternalServerError);
+ let key = chunk_idx.map(|ci| input_chunk_key(&mid_str, &job_id, ci));
+ let fs = state.file_storage_client.clone();
+ async move {
+ let key = key?;
+ let chunk_bytes = rows_to_csv_bytes(chunk_rows)?;
+ fs.upload_file(&key, chunk_bytes)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| format!("Failed to upload input chunk {idx}"))
+ }
+ })
+ .collect();
+
+ let results = future::join_all(upload_futures).await;
+ for result in results {
+ result?;
+ }
+
+ logger::info!(
+ job_id = %job_id,
+ chunk_total_count,
+ "Uploaded original CSV and all input chunks"
+ );
+ let now = date_time::now();
+
+ let total_rows_i32 = i32::try_from(total_rows)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Row count exceeds i32::MAX")?;
+
+ let job_new = storage::BatchBlocklistJobNew {
+ id: job_id.clone(),
+ merchant_id: merchant_id.clone(),
+ status: common_enums::BatchBlocklistJobStatus::Initiated,
+ total_rows: total_rows_i32,
+ succeeded_rows: 0,
+ failed_rows: 0,
+ created_at: now,
+ updated_at: now,
+ };
+
+ state
+ .store
+ .insert_batch_blocklist_job(job_new)
+ .await
+ .to_duplicate_response(errors::ApiErrorResponse::InternalServerError)?;
+
+ let tracking_data = storage::BatchBlocklistTrackingData {
+ job_id: job_id.clone(),
+ merchant_id: merchant_id.clone(),
+ chunk_total_count,
+ completed_chunks: Vec::new(),
+ };
+
+ let runner = storage::ProcessTrackerRunner::BatchBlocklistUpload;
+ let process_tracker_id =
+ pt_utils::get_process_tracker_id(runner, BATCH_BLOCKLIST_TASK, &job_id, merchant_id);
+
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ BATCH_BLOCKLIST_TASK,
+ runner,
+ BATCH_BLOCKLIST_TAGS,
+ tracking_data,
+ None,
+ date_time::now(),
+ common_types::consts::API_VERSION,
+ common_enums::ApplicationSource::Main,
+ )
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to create ProcessTrackerNew for batch blocklist job")?;
+
+ state
+ .store
+ .insert_process(process_tracker_entry)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to enqueue batch blocklist ProcessTracker task")?;
+
+ logger::info!(
+ job_id = %job_id,
+ total_rows,
+ chunk_total_count,
+ "Batch blocklist job initiated"
+ );
+
+ Ok(api_blocklist::BatchBlocklistUploadResponse {
+ job_id,
+ total_rows: u32::try_from(total_rows)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ status: common_enums::BatchBlocklistJobStatus::Initiated,
+ })
+}
+
+/// Bulk-inserts all rows in a single chunk into the blocklist table, returning the count of inserted rows.
+pub(crate) async fn process_chunk(
+ state: &SessionState,
+ merchant_id: &id_type::MerchantId,
+ chunk_idx: u32,
+ chunk_rows: Vec<BlocklistRow>,
+) -> RouterResult<i32> {
+ let now = date_time::now();
+ let entries: Vec<storage::BlocklistNew> = chunk_rows
+ .iter()
+ .map(|row| storage::BlocklistNew {
+ merchant_id: merchant_id.to_owned(),
+ fingerprint_id: row.data.clone(),
+ data_kind: row.data_kind,
+ metadata: row.metadata.clone(),
+ created_at: now,
+ })
+ .collect();
+
+ let succeeded = i32::try_from(entries.len())
+ .change_context(errors::ApiErrorResponse::InternalServerError)?;
+
+ state
+ .store
+ .bulk_insert_blocklist_entries(entries)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| format!("Bulk insert failed for chunk {chunk_idx}"))?;
+
+ logger::info!(chunk_idx, succeeded, "Bulk inserted batch blocklist chunk");
+
+ Ok(succeeded)
+}
+
+/// Fetches the status and row counters for a specific batch blocklist job.
+#[instrument(skip_all, fields(flow = ?router_env::Flow::GetBatchBlocklistJobStatus))]
+pub async fn get_batch_blocklist_job_status(
+ state: &SessionState,
+ merchant_id: &id_type::MerchantId,
+ job_id: &str,
+) -> RouterResult<api_blocklist::BatchBlocklistJobStatusResponse> {
+ let job = state
+ .store
+ .find_batch_blocklist_job_by_id_merchant_id(job_id, merchant_id.get_string_repr())
+ .await
+ .to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
+ message: format!("Batch blocklist job `{job_id}` not found"),
+ })?;
+
+ Ok(api_blocklist::BatchBlocklistJobStatusResponse {
+ job_id: job.id,
+ merchant_id: job.merchant_id.get_string_repr().to_owned(),
+ status: job.status,
+ total_rows: u32::try_from(job.total_rows)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ succeeded_rows: u32::try_from(job.succeeded_rows)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ failed_rows: u32::try_from(job.failed_rows)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ created_at: job.created_at,
+ updated_at: job.updated_at,
+ })
+}
+
+/// 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(
+ state: &SessionState,
+ merchant_id: &id_type::MerchantId,
+ query: api_blocklist::ListBatchBlocklistJobsQuery,
+) -> RouterResult<api_blocklist::ListBatchBlocklistJobsResponse> {
+ let limit = i64::from(query.limit.get());
+ let offset = i64::from(query.offset.get());
+
+ let (jobs, total_count) = future::try_join(
+ state.store.list_batch_blocklist_jobs_by_merchant_id(
+ merchant_id.get_string_repr(),
+ limit,
+ offset,
+ ),
+ state
+ .store
+ .count_batch_blocklist_jobs_by_merchant_id(merchant_id.get_string_repr()),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to list batch blocklist jobs")?;
+
+ let count = jobs.len();
+ let data = jobs
+ .into_iter()
+ .map(|job| {
+ Ok(api_blocklist::BatchBlocklistJobStatusResponse {
+ job_id: job.id,
+ merchant_id: job.merchant_id.get_string_repr().to_owned(),
+ status: job.status,
+ total_rows: u32::try_from(job.total_rows)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ succeeded_rows: u32::try_from(job.succeeded_rows)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ failed_rows: u32::try_from(job.failed_rows)
+ .change_context(errors::ApiErrorResponse::InternalServerError)?,
+ created_at: job.created_at,
+ updated_at: job.updated_at,
+ })
+ })
+ .collect::<RouterResult<Vec<_>>>()?;
+
+ Ok(api_blocklist::ListBatchBlocklistJobsResponse {
+ count,
+ total_count,
+ data,
+ })
+}
diff --git a/crates/router/src/core/blocklist/utils.rs b/crates/router/src/core/blocklist/utils.rs
index 0f8e36fac6..68ccfa2817 100644
--- a/crates/router/src/core/blocklist/utils.rs
+++ b/crates/router/src/core/blocklist/utils.rs
@@ -95,7 +95,7 @@ pub async fn list_blocklist_entries_for_merchant(
.store
.list_blocklist_entries_by_merchant_id_data_kind(
merchant_id,
- query.data_kind.clone(),
+ query.data_kind,
query.limit.into(),
query.offset.into(),
)
diff --git a/crates/router/src/db.rs b/crates/router/src/db.rs
index fa618b0300..654357f36d 100644
--- a/crates/router/src/db.rs
+++ b/crates/router/src/db.rs
@@ -2,6 +2,7 @@ pub mod address;
pub mod api_keys;
pub mod authentication;
pub mod authorization;
+pub mod batch_blocklist_job;
pub mod blocklist;
pub mod blocklist_fingerprint;
pub mod blocklist_lookup;
@@ -119,6 +120,7 @@ pub trait StorageInterface:
+ PaymentMethodInterface<Error = StorageError>
+ blocklist::BlocklistInterface
+ blocklist_fingerprint::BlocklistFingerprintInterface
+ + batch_blocklist_job::BatchBlocklistJobInterface
+ CardIssuersInterface<Error = StorageError>
+ dynamic_routing_stats::DynamicRoutingStatsInterface
+ scheduler::SchedulerInterface
diff --git a/crates/router/src/db/batch_blocklist_job.rs b/crates/router/src/db/batch_blocklist_job.rs
new file mode 100644
index 0000000000..0e70aac549
--- /dev/null
+++ b/crates/router/src/db/batch_blocklist_job.rs
@@ -0,0 +1,271 @@
+use error_stack::report;
+use router_env::{instrument, tracing};
+use storage_impl::MockDb;
+
+use super::Store;
+use crate::{
+ connection,
+ core::errors::{self, CustomResult},
+ db::kafka_store::KafkaStore,
+ types::storage,
+};
+
+#[async_trait::async_trait]
+pub trait BatchBlocklistJobInterface {
+ async fn insert_batch_blocklist_job(
+ &self,
+ new: storage::BatchBlocklistJobNew,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError>;
+
+ async fn find_batch_blocklist_job_by_id_merchant_id(
+ &self,
+ id: &str,
+ merchant_id: &str,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError>;
+
+ async fn list_batch_blocklist_jobs_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ limit: i64,
+ offset: i64,
+ ) -> CustomResult<Vec<storage::BatchBlocklistJob>, errors::StorageError>;
+
+ async fn update_batch_blocklist_job_by_id_merchant_id(
+ &self,
+ id: &str,
+ merchant_id: &str,
+ update: storage::BatchBlocklistJobUpdate,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError>;
+
+ async fn count_batch_blocklist_jobs_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ ) -> CustomResult<usize, errors::StorageError>;
+}
+
+#[async_trait::async_trait]
+impl BatchBlocklistJobInterface for Store {
+ #[instrument(skip_all)]
+ async fn insert_batch_blocklist_job(
+ &self,
+ new: storage::BatchBlocklistJobNew,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ new.insert(&conn)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn find_batch_blocklist_job_by_id_merchant_id(
+ &self,
+ id: &str,
+ merchant_id: &str,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::BatchBlocklistJob::find_by_id_merchant_id(&conn, id, merchant_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn list_batch_blocklist_jobs_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ limit: i64,
+ offset: i64,
+ ) -> CustomResult<Vec<storage::BatchBlocklistJob>, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::BatchBlocklistJob::list_by_merchant_id(&conn, merchant_id, limit, offset)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn update_batch_blocklist_job_by_id_merchant_id(
+ &self,
+ id: &str,
+ merchant_id: &str,
+ update: storage::BatchBlocklistJobUpdate,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::BatchBlocklistJob::update_by_id_merchant_id(&conn, id, merchant_id, update)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn count_batch_blocklist_jobs_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ ) -> CustomResult<usize, errors::StorageError> {
+ let conn = connection::pg_connection_read(self).await?;
+ storage::BatchBlocklistJob::count_by_merchant_id(&conn, merchant_id)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+}
+
+#[async_trait::async_trait]
+impl BatchBlocklistJobInterface for MockDb {
+ #[instrument(skip_all)]
+ async fn insert_batch_blocklist_job(
+ &self,
+ new: storage::BatchBlocklistJobNew,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {
+ let mut jobs = self.batch_blocklist_jobs.lock().await;
+ if jobs.iter().any(|j| j.id == new.id) {
+ Err(errors::StorageError::MockDbError)?
+ }
+ let job = storage::BatchBlocklistJob {
+ id: new.id,
+ merchant_id: new.merchant_id,
+ status: new.status,
+ total_rows: new.total_rows,
+ succeeded_rows: new.succeeded_rows,
+ failed_rows: new.failed_rows,
+ created_at: new.created_at,
+ updated_at: new.updated_at,
+ };
+ jobs.push(job.clone());
+ Ok(job)
+ }
+
+ #[instrument(skip_all)]
+ async fn find_batch_blocklist_job_by_id_merchant_id(
+ &self,
+ id: &str,
+ merchant_id: &str,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {
+ self.batch_blocklist_jobs
+ .lock()
+ .await
+ .iter()
+ .find(|j| j.id == id && j.merchant_id.get_string_repr() == merchant_id)
+ .cloned()
+ .ok_or(
+ errors::StorageError::ValueNotFound(format!(
+ "BatchBlocklistJob not found for id = {id} and merchant_id = {merchant_id}"
+ ))
+ .into(),
+ )
+ }
+
+ #[instrument(skip_all)]
+ async fn list_batch_blocklist_jobs_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ limit: i64,
+ offset: i64,
+ ) -> CustomResult<Vec<storage::BatchBlocklistJob>, errors::StorageError> {
+ Ok(self
+ .batch_blocklist_jobs
+ .lock()
+ .await
+ .iter()
+ .filter(|j| j.merchant_id.get_string_repr() == merchant_id)
+ .cloned()
+ .collect::<Vec<_>>()
+ .into_iter()
+ .skip(usize::try_from(offset).unwrap_or(0))
+ .take(usize::try_from(limit).unwrap_or(usize::MAX))
+ .collect())
+ }
+
+ #[instrument(skip_all)]
+ async fn update_batch_blocklist_job_by_id_merchant_id(
+ &self,
+ id: &str,
+ merchant_id: &str,
+ update: storage::BatchBlocklistJobUpdate,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {
+ let mut jobs = self.batch_blocklist_jobs.lock().await;
+ let job = jobs
+ .iter_mut()
+ .find(|j| j.id == id && j.merchant_id.get_string_repr() == merchant_id)
+ .ok_or(errors::StorageError::ValueNotFound(format!(
+ "BatchBlocklistJob not found for id = {id} and merchant_id = {merchant_id}"
+ )))?;
+ if let Some(status) = update.status {
+ job.status = status;
+ }
+ if let Some(succeeded_rows) = update.succeeded_rows {
+ job.succeeded_rows = succeeded_rows;
+ }
+ if let Some(failed_rows) = update.failed_rows {
+ job.failed_rows = failed_rows;
+ }
+ job.updated_at = update.updated_at;
+ Ok(job.clone())
+ }
+
+ #[instrument(skip_all)]
+ async fn count_batch_blocklist_jobs_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ ) -> CustomResult<usize, errors::StorageError> {
+ Ok(self
+ .batch_blocklist_jobs
+ .lock()
+ .await
+ .iter()
+ .filter(|j| j.merchant_id.get_string_repr() == merchant_id)
+ .count())
+ }
+}
+
+#[async_trait::async_trait]
+impl BatchBlocklistJobInterface for KafkaStore {
+ #[instrument(skip_all)]
+ async fn insert_batch_blocklist_job(
+ &self,
+ new: storage::BatchBlocklistJobNew,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {
+ self.diesel_store.insert_batch_blocklist_job(new).await
+ }
+
+ #[instrument(skip_all)]
+ async fn find_batch_blocklist_job_by_id_merchant_id(
+ &self,
+ id: &str,
+ merchant_id: &str,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {
+ self.diesel_store
+ .find_batch_blocklist_job_by_id_merchant_id(id, merchant_id)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn list_batch_blocklist_jobs_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ limit: i64,
+ offset: i64,
+ ) -> CustomResult<Vec<storage::BatchBlocklistJob>, errors::StorageError> {
+ self.diesel_store
+ .list_batch_blocklist_jobs_by_merchant_id(merchant_id, limit, offset)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn update_batch_blocklist_job_by_id_merchant_id(
+ &self,
+ id: &str,
+ merchant_id: &str,
+ update: storage::BatchBlocklistJobUpdate,
+ ) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError> {
+ self.diesel_store
+ .update_batch_blocklist_job_by_id_merchant_id(id, merchant_id, update)
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn count_batch_blocklist_jobs_by_merchant_id(
+ &self,
+ merchant_id: &str,
+ ) -> CustomResult<usize, errors::StorageError> {
+ self.diesel_store
+ .count_batch_blocklist_jobs_by_merchant_id(merchant_id)
+ .await
+ }
+}
diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rs
index bc7c405483..c19ac099c5 100644
--- a/crates/router/src/db/blocklist.rs
+++ b/crates/router/src/db/blocklist.rs
@@ -47,6 +47,14 @@ pub trait BlocklistInterface {
merchant_id: &common_utils::id_type::MerchantId,
data_kind: common_enums::BlocklistDataKind,
) -> CustomResult<usize, errors::StorageError>;
+
+ /// Bulk insert entries with `ON CONFLICT DO NOTHING`.
+ /// Returns the number of rows *newly* inserted.
+ /// Rows already present are silently skipped (not an error).
+ async fn bulk_insert_blocklist_entries(
+ &self,
+ entries: Vec<storage::BlocklistNew>,
+ ) -> CustomResult<usize, errors::StorageError>;
}
#[async_trait::async_trait]
@@ -133,6 +141,17 @@ impl BlocklistInterface for Store {
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
+
+ #[instrument(skip_all)]
+ async fn bulk_insert_blocklist_entries(
+ &self,
+ entries: Vec<storage::BlocklistNew>,
+ ) -> CustomResult<usize, errors::StorageError> {
+ let conn = connection::pg_connection_write(self).await?;
+ storage::BlocklistNew::bulk_insert_on_conflict_do_nothing(&conn, entries)
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
}
#[async_trait::async_trait]
@@ -185,6 +204,30 @@ impl BlocklistInterface for MockDb {
) -> CustomResult<storage::Blocklist, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
+
+ async fn bulk_insert_blocklist_entries(
+ &self,
+ entries: Vec<storage::BlocklistNew>,
+ ) -> CustomResult<usize, errors::StorageError> {
+ let mut blocklists = self.blocklists.lock().await;
+ let mut inserted = 0usize;
+ for entry in entries {
+ let already_exists = blocklists.iter().any(|b| {
+ b.merchant_id == entry.merchant_id && b.fingerprint_id == entry.fingerprint_id
+ });
+ if !already_exists {
+ blocklists.push(storage::Blocklist {
+ merchant_id: entry.merchant_id,
+ fingerprint_id: entry.fingerprint_id,
+ data_kind: entry.data_kind,
+ metadata: entry.metadata,
+ created_at: entry.created_at,
+ });
+ inserted += 1;
+ }
+ }
+ Ok(inserted)
+ }
}
#[async_trait::async_trait]
@@ -252,4 +295,14 @@ impl BlocklistInterface for KafkaStore {
.list_blocklist_entries_by_merchant_id(merchant_id)
.await
}
+
+ #[instrument(skip_all)]
+ async fn bulk_insert_blocklist_entries(
+ &self,
+ entries: Vec<storage::BlocklistNew>,
+ ) -> CustomResult<usize, errors::StorageError> {
+ self.diesel_store
+ .bulk_insert_blocklist_entries(entries)
+ .await
+ }
}
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 0e5af56eb3..076fc11626 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1860,6 +1860,15 @@ impl Blocklist {
.service(
web::resource("/toggle").route(web::post().to(blocklist::toggle_blocklist_guard)),
)
+ .service(
+ web::resource("/batch")
+ .route(web::post().to(blocklist::upload_batch_blocklist))
+ .route(web::get().to(blocklist::list_batch_blocklist_jobs)),
+ )
+ .service(
+ web::resource("/batch/{job_id}")
+ .route(web::get().to(blocklist::get_batch_blocklist_job_status)),
+ )
}
}
diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs
index ad2858885d..564cc0a7f1 100644
--- a/crates/router/src/routes/blocklist.rs
+++ b/crates/router/src/routes/blocklist.rs
@@ -1,3 +1,4 @@
+use actix_multipart::form::{bytes::Bytes as MultipartBytes, MultipartForm};
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::blocklist as api_blocklist;
use error_stack::report;
@@ -198,3 +199,156 @@ pub async fn toggle_blocklist_guard(
))
.await
}
+
+// ---- Batch blocklist upload route handlers ----
+
+#[derive(Debug, MultipartForm)]
+pub struct BatchBlocklistUploadForm {
+ #[multipart(limit = "5MB")]
+ pub file: MultipartBytes,
+}
+
+#[utoipa::path(
+ post,
+ path = "/blocklist/batch",
+ request_body(
+ content = String,
+ content_type = "multipart/form-data",
+ description = "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MB). \
+ The CSV must have a header row: `type,data,metadata`. \
+ `type`: one of `card_bin` (6 digits), `extended_card_bin` (8 digits), `fingerprint`. \
+ `metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). \
+ Maximum 100,000 data rows.",
+ ),
+ responses(
+ (status = 202, description = "Batch blocklist job initiated", body = BatchBlocklistUploadResponse),
+ (status = 400, description = "CSV validation error or file exceeds 5 MB limit"),
+ ),
+ tag = "Blocklist",
+ operation_id = "Upload a batch blocklist CSV",
+ security(("api_key" = []))
+)]
+pub async fn upload_batch_blocklist(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ MultipartForm(form): MultipartForm<BatchBlocklistUploadForm>,
+) -> HttpResponse {
+ let flow = Flow::BatchBlocklistUpload;
+ let csv_bytes = bytes::Bytes::from(form.file.data.to_vec());
+
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth: auth::AuthenticationData, _payload, _| {
+ let csv_bytes = csv_bytes.clone();
+ async move { blocklist::upload_batch_blocklist(state, auth.platform, csv_bytes).await }
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ allow_connected_scope_operation: false,
+ allow_platform_self_operation: false,
+ }),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountWrite,
+ allow_connected: false,
+ allow_platform: false,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[utoipa::path(
+ get,
+ path = "/blocklist/batch/{job_id}",
+ params(
+ ("job_id" = String, Path, description = "The job ID returned by the batch upload endpoint"),
+ ),
+ responses(
+ (status = 200, description = "Batch blocklist job status", body = BatchBlocklistJobStatusResponse),
+ (status = 404, description = "Job not found"),
+ ),
+ tag = "Blocklist",
+ operation_id = "Get batch blocklist job status",
+ security(("api_key" = []))
+)]
+pub async fn get_batch_blocklist_job_status(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ path: web::Path<String>,
+) -> HttpResponse {
+ let flow = Flow::GetBatchBlocklistJobStatus;
+ let job_id = path.into_inner();
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ job_id,
+ |state, auth: auth::AuthenticationData, job_id, _| {
+ blocklist::get_batch_blocklist_job_status(state, auth.platform, job_id)
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ allow_connected_scope_operation: false,
+ allow_platform_self_operation: false,
+ }),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountRead,
+ allow_connected: false,
+ allow_platform: false,
+ },
+ req.headers(),
+ ),
+ api_locking::LockAction::NotApplicable,
+ ))
+ .await
+}
+
+#[utoipa::path(
+ get,
+ path = "/blocklist/batch",
+ params(
+ ("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)"),
+ ),
+ responses(
+ (status = 200, description = "List of batch blocklist jobs", body = ListBatchBlocklistJobsResponse),
+ ),
+ tag = "Blocklist",
+ operation_id = "List batch blocklist jobs",
+ security(("api_key" = []))
+)]
+pub async fn list_batch_blocklist_jobs(
+ state: web::Data<AppState>,
+ req: HttpRequest,
+ query_payload: web::Query<api_blocklist::ListBatchBlocklistJobsQuery>,
+) -> HttpResponse {
+ let flow = Flow::ListBatchBlocklistJobs;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ query_payload.into_inner(),
+ |state, auth: auth::AuthenticationData, query, _| {
+ blocklist::list_batch_blocklist_jobs(state, auth.platform, query)
+ },
+ auth::auth_type(
+ &auth::HeaderAuth(auth::ApiKeyAuth {
+ allow_connected_scope_operation: false,
+ allow_platform_self_operation: false,
+ }),
+ &auth::JWTAuth {
+ permission: Permission::MerchantAccountRead,
+ allow_connected: false,
+ 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.rs
index 460803abc2..f15a281392 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -105,6 +105,9 @@ impl From<Flow> for ApiIdentifier {
Flow::DeleteFromBlocklist => Self::Blocklist,
Flow::ListBlocklist => Self::Blocklist,
Flow::ToggleBlocklistGuard => Self::Blocklist,
+ Flow::BatchBlocklistUpload => Self::Blocklist,
+ Flow::GetBatchBlocklistJobStatus => Self::Blocklist,
+ Flow::ListBatchBlocklistJobs => Self::Blocklist,
Flow::MerchantConnectorsCreate
| Flow::MerchantConnectorsRetrieve
| Flow::MerchantConnectorsUpdate
diff --git a/crates/router/src/types/storage.rs b/crates/router/src/types/storage.rs
index cbe8b81d0d..95793fc83f 100644
--- a/crates/router/src/types/storage.rs
+++ b/crates/router/src/types/storage.rs
@@ -2,6 +2,7 @@ pub mod address;
pub mod api_keys;
pub mod authentication;
pub mod authorization;
+pub mod batch_blocklist_job;
pub mod blocklist;
pub mod blocklist_fingerprint;
pub mod blocklist_lookup;
@@ -70,13 +71,13 @@ pub use hyperswitch_domain_models::{
pub use scheduler::db::process_tracker;
pub use self::{
- address::*, api_keys::*, authentication::*, authorization::*, blocklist::*,
- blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*, callback_mapper::*,
- capture::*, card_issuer::*, cards_info::*, configs::*, customers::*, dashboard_metadata::*,
- dispute::*, dynamic_routing_stats::*, ephemeral_key::*, events::*, file::*, fraud_check::*,
- generic_link::*, gsm::*, hyperswitch_ai_interaction::*, locker_mock_up::*, mandate::*,
- merchant_account::*, merchant_connector_account::*, merchant_key_store::*, payment_link::*,
- payment_method::*, process_tracker::*, refund::*, reverse_lookup::*, role::*,
- routing_algorithm::*, unified_translations::*, user::*, user_authentication_method::*,
- user_role::*,
+ address::*, api_keys::*, authentication::*, authorization::*, batch_blocklist_job::*,
+ blocklist::*, blocklist_fingerprint::*, blocklist_lookup::*, business_profile::*,
+ callback_mapper::*, capture::*, card_issuer::*, cards_info::*, configs::*, customers::*,
+ dashboard_metadata::*, dispute::*, dynamic_routing_stats::*, ephemeral_key::*, events::*,
+ file::*, fraud_check::*, generic_link::*, gsm::*, hyperswitch_ai_interaction::*,
+ locker_mock_up::*, mandate::*, merchant_account::*, merchant_connector_account::*,
+ merchant_key_store::*, payment_link::*, payment_method::*, process_tracker::*, refund::*,
+ reverse_lookup::*, role::*, routing_algorithm::*, unified_translations::*, user::*,
+ user_authentication_method::*, user_role::*,
};
diff --git a/crates/router/src/types/storage/batch_blocklist_job.rs b/crates/router/src/types/storage/batch_blocklist_job.rs
new file mode 100644
index 0000000000..7804df53a4
--- /dev/null
+++ b/crates/router/src/types/storage/batch_blocklist_job.rs
@@ -0,0 +1,12 @@
+use common_utils::id_type;
+pub use diesel_models::batch_blocklist_job::{
+ BatchBlocklistJob, BatchBlocklistJobNew, BatchBlocklistJobUpdate,
+};
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct BatchBlocklistTrackingData {
+ pub job_id: String,
+ pub merchant_id: id_type::MerchantId,
+ pub chunk_total_count: u32,
+ pub completed_chunks: Vec<u32>,
+}
diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs
index 093d6d1ba6..ca0c4b2f1a 100644
--- a/crates/router/src/workflows.rs
+++ b/crates/router/src/workflows.rs
@@ -21,3 +21,6 @@ pub mod invoice_sync;
#[cfg(feature = "payouts")]
pub mod payout_sync;
+
+#[cfg(feature = "v1")]
+pub mod batch_blocklist_upload;
diff --git a/crates/router/src/workflows/batch_blocklist_upload.rs b/crates/router/src/workflows/batch_blocklist_upload.rs
new file mode 100644
index 0000000000..93d8525635
--- /dev/null
+++ b/crates/router/src/workflows/batch_blocklist_upload.rs
@@ -0,0 +1,278 @@
+use common_utils::{ext_traits::ValueExt, id_type};
+use error_stack::ResultExt;
+use router_env::{instrument, tracing};
+use scheduler::{
+ consumer::{self, types::process_data},
+ utils as pt_utils,
+ workflows::ProcessTrackerWorkflow,
+};
+
+use crate::{
+ core::{
+ blocklist::batch,
+ errors::{self, RouterResult},
+ },
+ logger::{error, info, warn},
+ routes::SessionState,
+ types::storage,
+};
+
+pub struct BatchBlocklistUploadWorkflow;
+
+/// Processes all unfinished chunks for a batch blocklist job, inserting entries and updating progress after each chunk.
+async fn run_batch_job(
+ state: &SessionState,
+ process_id: &str,
+ mut tracking_data: storage::BatchBlocklistTrackingData,
+ merchant_id_obj: &id_type::MerchantId,
+) -> RouterResult<(i32, i32)> {
+ let db = &*state.store;
+ let job_id = &tracking_data.job_id;
+ let merchant_id_str = merchant_id_obj.get_string_repr();
+ let n_chunks = tracking_data.chunk_total_count;
+
+ // Seed from persisted count so retries accumulate correctly.
+ let existing_job = db
+ .find_batch_blocklist_job_by_id_merchant_id(job_id, merchant_id_str)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to fetch job for counter seeding")?;
+ let total_rows = existing_job.total_rows;
+ let mut total_succeeded: i32 = existing_job.succeeded_rows;
+
+ for chunk_idx in 0..n_chunks {
+ if tracking_data.completed_chunks.contains(&chunk_idx) {
+ continue;
+ }
+
+ let input_key = batch::input_chunk_key(merchant_id_str, job_id, chunk_idx);
+ let chunk_bytes = state
+ .file_storage_client
+ .retrieve_file(&input_key)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!("Failed to retrieve input chunk {chunk_idx} for job {job_id}")
+ })?;
+
+ let chunk_rows = batch::parse_chunk_csv(&chunk_bytes)?;
+
+ let chunk_succeeded =
+ batch::process_chunk(state, merchant_id_obj, chunk_idx, chunk_rows).await?;
+ total_succeeded += chunk_succeeded;
+
+ tracking_data.completed_chunks.push(chunk_idx);
+ let td_value = serde_json::to_value(&tracking_data)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialise updated tracking_data")?;
+
+ db.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_lazy(|| {
+ format!("Failed to update tracking_data after chunk {chunk_idx}")
+ })?;
+
+ db.update_batch_blocklist_job_by_id_merchant_id(
+ job_id,
+ merchant_id_str,
+ storage::BatchBlocklistJobUpdate {
+ status: None,
+ succeeded_rows: Some(total_succeeded),
+ failed_rows: None,
+ updated_at: common_utils::date_time::now(),
+ },
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!("Failed to update progress counters after chunk {chunk_idx}")
+ })?;
+
+ info!(
+ job_id = %job_id,
+ chunk_idx,
+ n_chunks,
+ completed_chunks = tracking_data.completed_chunks.len(),
+ chunk_succeeded,
+ "Processed batch blocklist chunk"
+ );
+ }
+
+ Ok((total_succeeded, total_rows))
+}
+
+/// Deletes all input chunk files from file storage after a job completes.
+async fn delete_input_chunks(
+ state: &SessionState,
+ merchant_id: &id_type::MerchantId,
+ job_id: &str,
+ chunk_total_count: u32,
+) -> RouterResult<()> {
+ for chunk_idx in 0..chunk_total_count {
+ let input_key = batch::input_chunk_key(merchant_id.get_string_repr(), job_id, chunk_idx);
+ state
+ .file_storage_client
+ .delete_file(&input_key)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!("Failed to delete input chunk {chunk_idx} for job {job_id}")
+ })?;
+ }
+
+ Ok(())
+}
+
+#[async_trait::async_trait]
+impl ProcessTrackerWorkflow<SessionState> for BatchBlocklistUploadWorkflow {
+ /// Deserializes tracking data, runs all pending chunks, then marks the job completed or schedules a retry on failure.
+ #[instrument(skip_all, fields(flow = ?router_env::Flow::BatchBlocklistUpload))]
+ async fn execute_workflow<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ let db = &*state.store;
+
+ let tracking_data: storage::BatchBlocklistTrackingData = process
+ .tracking_data
+ .clone()
+ .parse_value("BatchBlocklistTrackingData")
+ .map_err(errors::ProcessTrackerError::from)?;
+
+ let job_id = tracking_data.job_id.clone();
+ let chunk_total_count = tracking_data.chunk_total_count;
+
+ let merchant_id = tracking_data.merchant_id.clone();
+ let merchant_id_str = merchant_id.get_string_repr();
+
+ if tracking_data.completed_chunks.is_empty() {
+ db.update_batch_blocklist_job_by_id_merchant_id(
+ &job_id,
+ merchant_id_str,
+ storage::BatchBlocklistJobUpdate {
+ status: Some(common_enums::BatchBlocklistJobStatus::Processing),
+ succeeded_rows: None,
+ failed_rows: None,
+ updated_at: common_utils::date_time::now(),
+ },
+ )
+ .await
+ .map_err(errors::ProcessTrackerError::from)?;
+ }
+
+ let result = run_batch_job(state, &process.id, tracking_data, &merchant_id).await;
+
+ match result {
+ Ok((succeeded_rows, total_rows)) => {
+ let failed_rows = total_rows - succeeded_rows;
+ db.update_batch_blocklist_job_by_id_merchant_id(
+ &job_id,
+ merchant_id_str,
+ storage::BatchBlocklistJobUpdate {
+ status: Some(common_enums::BatchBlocklistJobStatus::Completed),
+ succeeded_rows: Some(succeeded_rows),
+ failed_rows: Some(failed_rows),
+ updated_at: common_utils::date_time::now(),
+ },
+ )
+ .await
+ .map_err(errors::ProcessTrackerError::from)?;
+
+ if let Err(error) =
+ delete_input_chunks(state, &merchant_id, &job_id, chunk_total_count).await
+ {
+ warn!(
+ job_id = %job_id,
+ error = ?error,
+ "Failed to clean up batch blocklist input chunks after completion"
+ );
+ }
+
+ db.as_scheduler()
+ .finish_process_with_business_status(process, "COMPLETED_BY_PT")
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?;
+ }
+ Err(err) => {
+ let retry_count = process.retry_count;
+ error!(
+ job_id = %job_id,
+ error = ?err,
+ "Batch blocklist processing failed (retry_count={})",
+ retry_count
+ );
+
+ let mapping = process_data::RetryMapping::default();
+ let time_delta = if retry_count == 0 {
+ Some(mapping.start_after)
+ } else {
+ pt_utils::get_delay(retry_count + 1, &mapping.frequencies)
+ };
+ let schedule_time = pt_utils::get_time_from_delta(time_delta);
+
+ match schedule_time {
+ Some(s_time) => {
+ db.as_scheduler()
+ .retry_process(process, s_time)
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?;
+ }
+ None => {
+ warn!(
+ job_id = %job_id,
+ "Batch blocklist job exceeded max retries, marking failed"
+ );
+ let current_job = db
+ .find_batch_blocklist_job_by_id_merchant_id(&job_id, merchant_id_str)
+ .await
+ .map_err(errors::ProcessTrackerError::from)?;
+ let failed_rows = current_job.total_rows - current_job.succeeded_rows;
+ db.update_batch_blocklist_job_by_id_merchant_id(
+ &job_id,
+ merchant_id_str,
+ storage::BatchBlocklistJobUpdate {
+ status: Some(common_enums::BatchBlocklistJobStatus::Failed),
+ succeeded_rows: None,
+ failed_rows: Some(failed_rows),
+ updated_at: common_utils::date_time::now(),
+ },
+ )
+ .await
+ .map_err(errors::ProcessTrackerError::from)?;
+
+ db.as_scheduler()
+ .finish_process_with_business_status(process, "RETRIES_EXCEEDED")
+ .await
+ .map_err(Into::<errors::ProcessTrackerError>::into)?;
+ }
+ }
+ }
+ }
+
+ Ok(())
+ }
+
+ /// Delegates to the standard consumer error handler to reschedule or mark the process as failed.
+ async fn error_handler<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ error: errors::ProcessTrackerError,
+ ) -> errors::CustomResult<(), errors::ProcessTrackerError> {
+ consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
+ }
+}
diff --git a/crates/router_env/src/logger/types.rs b/crates/router_env/src/logger/types.rs
index d259841b65..93b119c1f7 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -321,6 +321,12 @@ pub enum Flow {
ListBlocklist,
/// Toggle blocklist for merchant
ToggleBlocklistGuard,
+ /// Bulk upload blocklist entries via CSV
+ BatchBlocklistUpload,
+ /// Get status of a batch blocklist upload job
+ GetBatchBlocklistJobStatus,
+ /// List batch blocklist upload jobs for a merchant
+ ListBatchBlocklistJobs,
/// Incoming Webhook Receive
IncomingWebhookReceive,
/// Recovery incoming webhook receive
diff --git a/crates/storage_impl/src/mock_db.rs b/crates/storage_impl/src/mock_db.rs
index 2007a107e2..9171845ee8 100644
--- a/crates/storage_impl/src/mock_db.rs
+++ b/crates/storage_impl/src/mock_db.rs
@@ -68,6 +68,8 @@ pub struct MockDb {
pub hyperswitch_ai_interactions:
Arc<Mutex<Vec<store::hyperswitch_ai_interaction::HyperswitchAiInteraction>>>,
pub card_issuers: Arc<Mutex<Vec<store::card_issuer::CardIssuer>>>,
+ pub blocklists: Arc<Mutex<Vec<store::blocklist::Blocklist>>>,
+ pub batch_blocklist_jobs: Arc<Mutex<Vec<store::batch_blocklist_job::BatchBlocklistJob>>>,
pub key_manager_state: Option<KeyManagerState>,
}
@@ -127,6 +129,8 @@ impl MockDb {
themes: Default::default(),
hyperswitch_ai_interactions: Default::default(),
card_issuers: Default::default(),
+ blocklists: Default::default(),
+ batch_blocklist_jobs: Default::default(),
key_manager_state: Some(key_manager_state),
})
}
diff --git a/migrations/2026-05-01-145200_create_batch_blocklist_jobs_table/down.sql b/migrations/2026-05-01-145200_create_batch_blocklist_jobs_table/down.sql
new file mode 100644
index 0000000000..7c5b214d22
--- /dev/null
+++ b/migrations/2026-05-01-145200_create_batch_blocklist_jobs_table/down.sql
@@ -0,0 +1 @@
+DROP TABLE IF EXISTS batch_blocklist_jobs;
diff --git a/migrations/2026-05-01-145200_create_batch_blocklist_jobs_table/up.sql b/migrations/2026-05-01-145200_create_batch_blocklist_jobs_table/up.sql
new file mode 100644
index 0000000000..4d3998a9fd
--- /dev/null
+++ b/migrations/2026-05-01-145200_create_batch_blocklist_jobs_table/up.sql
@@ -0,0 +1,13 @@
+CREATE TABLE batch_blocklist_jobs (
+ id VARCHAR(64) PRIMARY KEY,
+ merchant_id VARCHAR(64) NOT NULL,
+ status VARCHAR(32) NOT NULL,
+ total_rows INTEGER NOT NULL,
+ succeeded_rows INTEGER NOT NULL,
+ failed_rows INTEGER NOT NULL,
+ created_at TIMESTAMP NOT NULL,
+ updated_at TIMESTAMP NOT NULL
+);
+
+CREATE INDEX batch_blocklist_jobs_merchant_id_created_at_idx
+ ON batch_blocklist_jobs (merchant_id);