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): export a merchant's blocklist data as a CSV (#14078)

Ayush Anand2b210c02bc64
diff --git a/api-reference/docs.json b/api-reference/docs.json
index 8da40e26d4..aa580cf1ac 100644
--- a/api-reference/docs.json
+++ b/api-reference/docs.json
@@ -282,7 +282,8 @@
"v1/blocklist/blocklist--lookup",
"v1/blocklist/blocklist--batch-upload",
"v1/blocklist/blocklist--batch-list",
- "v1/blocklist/blocklist--batch-status"
+ "v1/blocklist/blocklist--batch-status",
+ "v1/blocklist/blocklist--export-create"
]
},
{
diff --git a/api-reference/v1/blocklist/blocklist--export-create.mdx b/api-reference/v1/blocklist/blocklist--export-create.mdx
new file mode 100644
index 0000000000..a2dfcccce9
--- /dev/null
+++ b/api-reference/v1/blocklist/blocklist--export-create.mdx
@@ -0,0 +1,3 @@
+---
+openapi: post /blocklist/export
+---
diff --git a/api-reference/v1/openapi_spec_v1.json b/api-reference/v1/openapi_spec_v1.json
index dc98f50d84..b6cebea994 100644
--- a/api-reference/v1/openapi_spec_v1.json
+++ b/api-reference/v1/openapi_spec_v1.json
@@ -7117,7 +7117,7 @@
}
],
"requestBody": {
- "description": "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MiB). The CSV must have a header row: `type,data,metadata`. `type`: one of `generic_card_bin` (6 to 10 digits), `fingerprint`. `metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). Maximum 100,000 data rows.",
+ "description": "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MiB). The part's `filename` is recorded on the job and returned as `file_name`. The CSV must have a header row: `type,data,metadata`. `type`: one of `generic_card_bin` (6 to 10 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": {
@@ -7177,11 +7177,35 @@
"nullable": true,
"minimum": 0
}
+ },
+ {
+ "name": "job_type",
+ "in": "query",
+ "description": "Restricts the listing to `upload` or `export` jobs. Both kinds are returned when omitted, newest first.",
+ "required": false,
+ "schema": {
+ "allOf": [
+ {
+ "$ref": "#/components/schemas/BatchBlocklistJobType"
+ }
+ ],
+ "nullable": true
+ }
+ },
+ {
+ "name": "X-Profile-Id",
+ "in": "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.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "nullable": true
+ }
}
],
"responses": {
"200": {
- "description": "List of batch blocklist jobs",
+ "description": "List of batch blocklist jobs. Rows report `downloadable`, but never `download_url` - fetch the link from `GET /blocklist/batch/{job_id}` when the merchant asks for that specific file.",
"content": {
"application/json": {
"schema": {
@@ -7208,7 +7232,7 @@
{
"name": "job_id",
"in": "path",
- "description": "The job ID returned by the batch upload endpoint",
+ "description": "The job ID returned by the batch upload endpoint, or the export ID returned by `POST /blocklist/export`",
"required": true,
"schema": {
"type": "string"
@@ -7217,7 +7241,7 @@
],
"responses": {
"200": {
- "description": "Batch blocklist job status",
+ "description": "Batch blocklist job status. For a completed export whose file is still stored, this is where the short-lived `download_url` is issued.",
"content": {
"application/json": {
"schema": {
@@ -7237,6 +7261,46 @@
]
}
},
+ "/blocklist/export": {
+ "post": {
+ "tags": [
+ "Blocklist"
+ ],
+ "operationId": "Start a blocklist CSV export",
+ "parameters": [
+ {
+ "name": "X-Profile-Id",
+ "in": "header",
+ "description": "The business profile whose blocklist is exported. Resolution follows the same rules as blocking a single entry.",
+ "required": false,
+ "schema": {
+ "type": "string",
+ "nullable": true
+ }
+ }
+ ],
+ "responses": {
+ "202": {
+ "description": "Blocklist export started",
+ "content": {
+ "application/json": {
+ "schema": {
+ "$ref": "#/components/schemas/BlocklistExportResponse"
+ }
+ }
+ }
+ },
+ "400": {
+ "description": "No profile could be resolved"
+ }
+ },
+ "security": [
+ {
+ "api_key": []
+ }
+ ]
+ }
+ },
"/payouts/create": {
"post": {
"tags": [
@@ -15661,16 +15725,18 @@
},
"BatchBlocklistJobStatusResponse": {
"type": "object",
- "description": "Response for `GET /blocklist/batch/{job_id}`.",
+ "description": "One batch blocklist job, as returned by the listing and by `GET /blocklist/batch/{job_id}`.",
"required": [
"job_id",
"merchant_id",
+ "job_type",
"status",
"total_rows",
"succeeded_rows",
"failed_rows",
"created_at",
- "updated_at"
+ "updated_at",
+ "downloadable"
],
"properties": {
"job_id": {
@@ -15679,6 +15745,14 @@
"merchant_id": {
"type": "string"
},
+ "job_type": {
+ "$ref": "#/components/schemas/BatchBlocklistJobType"
+ },
+ "file_name": {
+ "type": "string",
+ "description": "The file the merchant uploaded, or the name the export downloads as.",
+ "nullable": true
+ },
"status": {
"$ref": "#/components/schemas/BatchBlocklistJobStatus"
},
@@ -15704,9 +15778,41 @@
"updated_at": {
"type": "string",
"format": "date-time"
+ },
+ "expires_at": {
+ "type": "string",
+ "format": "date-time",
+ "description": "Exports only: when the stored file is removed by the storage lifecycle rule.",
+ "nullable": true
+ },
+ "downloadable": {
+ "type": "boolean",
+ "description": "Whether this job's file can be fetched right now."
+ },
+ "error_message": {
+ "type": "string",
+ "nullable": true
+ },
+ "download_url": {
+ "type": "string",
+ "description": "Exports only: short-lived signed link, generated per request and never stored. Null in the\nlisting, which does not mint a link per row.",
+ "nullable": true
+ },
+ "download_url_expires_at": {
+ "type": "string",
+ "format": "date-time",
+ "nullable": true
}
}
},
+ "BatchBlocklistJobType": {
+ "type": "string",
+ "description": "Distinguishes a bulk upload job from a CSV export job in the `batch_blocklist_jobs` table.",
+ "enum": [
+ "upload",
+ "export"
+ ]
+ },
"BatchBlocklistUploadResponse": {
"type": "object",
"description": "Response returned on a successful `POST /blocklist/batch`.",
@@ -15901,6 +16007,28 @@
"generic_card_bin"
]
},
+ "BlocklistExportResponse": {
+ "type": "object",
+ "description": "Response for `POST /blocklist/export`.",
+ "required": [
+ "export_id",
+ "status",
+ "file_name"
+ ],
+ "properties": {
+ "export_id": {
+ "type": "string",
+ "description": "Present for support and log correlation."
+ },
+ "status": {
+ "$ref": "#/components/schemas/BatchBlocklistJobStatus"
+ },
+ "file_name": {
+ "type": "string",
+ "description": "The name this export will download as."
+ }
+ }
+ },
"BlocklistLookupQuery": {
"type": "object",
"required": [
diff --git a/crates/api_models/src/blocklist.rs b/crates/api_models/src/blocklist.rs
index 0f59183b63..31d5019d31 100644
--- a/crates/api_models/src/blocklist.rs
+++ b/crates/api_models/src/blocklist.rs
@@ -5,9 +5,6 @@ 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 {
@@ -161,11 +158,16 @@ pub struct BatchBlocklistUploadResponse {
pub status: enums::BatchBlocklistJobStatus,
}
-/// Response for `GET /blocklist/batch/{job_id}`.
+/// One batch blocklist job, as returned by the listing and by `GET /blocklist/batch/{job_id}`.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct BatchBlocklistJobStatusResponse {
pub job_id: String,
pub merchant_id: String,
+ /// Whether this job imported entries or exported them.
+ #[schema(value_type = BatchBlocklistJobType)]
+ pub job_type: enums::BatchBlocklistJobType,
+ /// The file the merchant uploaded, or the name the export downloads as.
+ pub file_name: Option<String>,
#[schema(value_type = BatchBlocklistJobStatus)]
pub status: enums::BatchBlocklistJobStatus,
pub total_rows: u32,
@@ -175,59 +177,32 @@ pub struct BatchBlocklistJobStatusResponse {
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)?))
- }
+ /// Exports only: when the stored file is removed by the storage lifecycle rule.
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub expires_at: Option<time::PrimitiveDateTime>,
+ /// Whether this job's file can be fetched right now.
+ pub downloadable: bool,
+ pub error_message: Option<String>,
+ /// Exports only: short-lived signed link, generated per request and never stored. Null in the
+ /// listing, which does not mint a link per row.
+ #[schema(value_type = Option<String>)]
+ pub download_url: Option<hyperswitch_masking::Secret<url::Url>>,
+ #[serde(default, with = "common_utils::custom_serde::iso8601::option")]
+ pub download_url_expires_at: Option<time::PrimitiveDateTime>,
}
/// Query parameters for listing batch blocklist jobs.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ListBatchBlocklistJobsQuery {
+ /// Limit on the number of objects to return
#[serde(default)]
- pub limit: BatchListLimit,
+ pub limit: common_utils::types::list::PageSize,
+ /// The starting point within a list of objects
#[serde(default)]
- pub offset: BatchListOffset,
+ pub offset: common_utils::types::list::PageOffset,
+ /// Restricts the listing to one kind of job. Both uploads and exports are returned when omitted.
+ #[schema(value_type = Option<BatchBlocklistJobType>)]
+ pub job_type: Option<enums::BatchBlocklistJobType>,
}
/// Response for `GET /blocklist/batch`.
@@ -238,7 +213,21 @@ pub struct ListBatchBlocklistJobsResponse {
pub data: Vec<BatchBlocklistJobStatusResponse>,
}
+// ---- Blocklist CSV export types ----
+
+/// Response for `POST /blocklist/export`.
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
+pub struct BlocklistExportResponse {
+ /// Present for support and log correlation.
+ pub export_id: String,
+ #[schema(value_type = BatchBlocklistJobStatus)]
+ pub status: enums::BatchBlocklistJobStatus,
+ /// The name this export will download as.
+ pub file_name: String,
+}
+
impl ApiEventMetric for BatchBlocklistUploadResponse {}
impl ApiEventMetric for BatchBlocklistJobStatusResponse {}
impl ApiEventMetric for ListBatchBlocklistJobsQuery {}
impl ApiEventMetric for ListBatchBlocklistJobsResponse {}
+impl ApiEventMetric for BlocklistExportResponse {}
diff --git a/crates/common_enums/src/enums.rs b/crates/common_enums/src/enums.rs
index 1ece7276ab..22e987151f 100644
--- a/crates/common_enums/src/enums.rs
+++ b/crates/common_enums/src/enums.rs
@@ -11373,6 +11373,7 @@ pub enum ProcessTrackerRunner {
BatchBlocklistUpload,
NetworkTokenizationWorkflow,
OfferEngineNotifyWorkflow,
+ BlocklistExportWorkflow,
}
#[derive(
@@ -12049,6 +12050,27 @@ pub enum BatchBlocklistJobStatus {
Failed,
}
+/// Distinguishes a bulk upload job from a CSV export job in the `batch_blocklist_jobs` table.
+#[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 BatchBlocklistJobType {
+ Upload,
+ Export,
+}
+
#[derive(
Clone,
Copy,
diff --git a/crates/diesel_models/src/batch_blocklist_job.rs b/crates/diesel_models/src/batch_blocklist_job.rs
index f2354418ab..6697a3e4c1 100644
--- a/crates/diesel_models/src/batch_blocklist_job.rs
+++ b/crates/diesel_models/src/batch_blocklist_job.rs
@@ -1,4 +1,4 @@
-use common_enums::BatchBlocklistJobStatus;
+use common_enums::{BatchBlocklistJobStatus, BatchBlocklistJobType};
use common_utils::id_type;
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
@@ -18,6 +18,13 @@ pub struct BatchBlocklistJob {
pub created_at: PrimitiveDateTime,
pub updated_at: PrimitiveDateTime,
pub profile_id: Option<id_type::ProfileId>,
+ // Absent on rows written before exports existed; those are uploads.
+ pub job_type: Option<BatchBlocklistJobType>,
+ /// The merchant's own filename for an upload, or the name an export downloads as.
+ pub file_name: Option<String>,
+ pub file_key: Option<String>,
+ pub error_message: Option<String>,
+ pub expires_at: Option<PrimitiveDateTime>,
}
#[derive(Clone, Debug, Insertable, Deserialize, Serialize)]
@@ -32,6 +39,8 @@ pub struct BatchBlocklistJobNew {
pub created_at: PrimitiveDateTime,
pub updated_at: PrimitiveDateTime,
pub profile_id: id_type::ProfileId,
+ pub job_type: BatchBlocklistJobType,
+ pub file_name: Option<String>,
}
#[derive(Clone, Debug, AsChangeset)]
@@ -40,5 +49,9 @@ pub struct BatchBlocklistJobUpdate {
pub status: Option<BatchBlocklistJobStatus>,
pub succeeded_rows: Option<i32>,
pub failed_rows: Option<i32>,
+ pub total_rows: Option<i32>,
+ pub file_key: Option<String>,
+ pub error_message: Option<String>,
+ pub expires_at: Option<PrimitiveDateTime>,
pub updated_at: PrimitiveDateTime,
}
diff --git a/crates/diesel_models/src/query/batch_blocklist_job.rs b/crates/diesel_models/src/query/batch_blocklist_job.rs
index f8d420d082..8943b19a5d 100644
--- a/crates/diesel_models/src/query/batch_blocklist_job.rs
+++ b/crates/diesel_models/src/query/batch_blocklist_job.rs
@@ -1,3 +1,5 @@
+use common_enums::BatchBlocklistJobType;
+use common_utils::id_type;
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods};
use super::generics;
@@ -31,6 +33,7 @@ impl BatchBlocklistJob {
.await
}
+ // The listing and the count must be given the same filter, or the page and the total disagree.
pub async fn list_by_merchant_id(
conn: &DatabaseConnectionWithContext<'_>,
merchant_id: &str,
@@ -58,6 +61,121 @@ impl BatchBlocklistJob {
.await
}
+ pub async fn list_by_merchant_id_job_type(
+ conn: &DatabaseConnectionWithContext<'_>,
+ merchant_id: &str,
+ job_type: BatchBlocklistJobType,
+ limit: i64,
+ offset: i64,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::job_type.eq(job_type)),
+ Some(limit),
+ Some(offset),
+ Some(dsl::created_at.desc()),
+ )
+ .await
+ }
+
+ pub async fn count_by_merchant_id_job_type(
+ conn: &DatabaseConnectionWithContext<'_>,
+ merchant_id: &str,
+ job_type: BatchBlocklistJobType,
+ ) -> StorageResult<usize> {
+ generics::generic_count::<<Self as HasTable>::Table, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::job_type.eq(job_type)),
+ )
+ .await
+ }
+
+ pub async fn list_by_merchant_id_profile_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ merchant_id: &str,
+ profile_id: &id_type::ProfileId,
+ limit: i64,
+ offset: i64,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::merchant_id.eq(merchant_id.to_owned()).and(
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .or(dsl::profile_id.is_null()),
+ ),
+ Some(limit),
+ Some(offset),
+ Some(dsl::created_at.desc()),
+ )
+ .await
+ }
+
+ pub async fn count_by_merchant_id_profile_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ merchant_id: &str,
+ profile_id: &id_type::ProfileId,
+ ) -> StorageResult<usize> {
+ generics::generic_count::<<Self as HasTable>::Table, _>(
+ conn,
+ dsl::merchant_id.eq(merchant_id.to_owned()).and(
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .or(dsl::profile_id.is_null()),
+ ),
+ )
+ .await
+ }
+
+ pub async fn list_by_merchant_id_profile_id_job_type(
+ conn: &DatabaseConnectionWithContext<'_>,
+ merchant_id: &str,
+ profile_id: &id_type::ProfileId,
+ job_type: BatchBlocklistJobType,
+ limit: i64,
+ offset: i64,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::job_type.eq(job_type))
+ .and(
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .or(dsl::profile_id.is_null()),
+ ),
+ Some(limit),
+ Some(offset),
+ Some(dsl::created_at.desc()),
+ )
+ .await
+ }
+
+ pub async fn count_by_merchant_id_profile_id_job_type(
+ conn: &DatabaseConnectionWithContext<'_>,
+ merchant_id: &str,
+ profile_id: &id_type::ProfileId,
+ job_type: BatchBlocklistJobType,
+ ) -> StorageResult<usize> {
+ generics::generic_count::<<Self as HasTable>::Table, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::job_type.eq(job_type))
+ .and(
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .or(dsl::profile_id.is_null()),
+ ),
+ )
+ .await
+ }
+
pub async fn update_by_id_merchant_id(
conn: &DatabaseConnectionWithContext<'_>,
id: &str,
diff --git a/crates/diesel_models/src/query/blocklist.rs b/crates/diesel_models/src/query/blocklist.rs
index 2efac80cd4..4b61c31d97 100644
--- a/crates/diesel_models/src/query/blocklist.rs
+++ b/crates/diesel_models/src/query/blocklist.rs
@@ -354,6 +354,59 @@ impl Blocklist {
.await
}
+ pub async fn list_after_fingerprint_by_processor_merchant_id_profile_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ processor_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::processor_merchant_id
+ .eq(processor_merchant_id.to_owned())
+ .and(dsl::fingerprint_id.gt(after_fingerprint_id))
+ .and(dsl::created_at.le(snapshot_at))
+ .and(
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .or(dsl::profile_id.is_null()),
+ ),
+ Some(limit),
+ None,
+ Some(dsl::fingerprint_id.asc()),
+ )
+ .await
+ }
+
+ pub async fn list_after_fingerprint_by_legacy_merchant_id_profile_id(
+ conn: &DatabaseConnectionWithContext<'_>,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> StorageResult<Vec<Self>> {
+ generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
+ conn,
+ dsl::merchant_id
+ .eq(merchant_id.to_owned())
+ .and(dsl::processor_merchant_id.is_null())
+ .and(dsl::fingerprint_id.gt(after_fingerprint_id))
+ .and(dsl::created_at.le(snapshot_at))
+ .and(
+ dsl::profile_id
+ .eq(profile_id.to_owned())
+ .or(dsl::profile_id.is_null()),
+ ),
+ Some(limit),
+ None,
+ Some(dsl::fingerprint_id.asc()),
+ )
+ .await
+ }
+
pub async fn delete_by_processor_merchant_id_fingerprint_id(
conn: &DatabaseConnectionWithContext<'_>,
processor_merchant_id: &common_utils::id_type::MerchantId,
diff --git a/crates/diesel_models/src/schema.rs b/crates/diesel_models/src/schema.rs
index dd6e2c0083..36d9cc352d 100644
--- a/crates/diesel_models/src/schema.rs
+++ b/crates/diesel_models/src/schema.rs
@@ -204,6 +204,14 @@ diesel::table! {
updated_at -> Timestamp,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
+ #[max_length = 32]
+ job_type -> Nullable<Varchar>,
+ #[max_length = 255]
+ file_name -> Nullable<Varchar>,
+ #[max_length = 512]
+ file_key -> Nullable<Varchar>,
+ error_message -> Nullable<Text>,
+ expires_at -> Nullable<Timestamp>,
}
}
diff --git a/crates/diesel_models/src/schema_v2.rs b/crates/diesel_models/src/schema_v2.rs
index 5628457ff9..d30076ac82 100644
--- a/crates/diesel_models/src/schema_v2.rs
+++ b/crates/diesel_models/src/schema_v2.rs
@@ -204,6 +204,14 @@ diesel::table! {
updated_at -> Timestamp,
#[max_length = 64]
profile_id -> Nullable<Varchar>,
+ #[max_length = 32]
+ job_type -> Nullable<Varchar>,
+ #[max_length = 255]
+ file_name -> Nullable<Varchar>,
+ #[max_length = 512]
+ file_key -> Nullable<Varchar>,
+ error_message -> Nullable<Text>,
+ expires_at -> Nullable<Timestamp>,
}
}
diff --git a/crates/external_services/src/file_storage.rs b/crates/external_services/src/file_storage.rs
index 479b7c5f38..cb1966083e 100644
--- a/crates/external_services/src/file_storage.rs
+++ b/crates/external_services/src/file_storage.rs
@@ -64,6 +64,46 @@ pub trait FileStorageInterface: dyn_clone::DynClone + Sync + Send {
/// Retrieves a file from the selected storage scheme.
async fn retrieve_file(&self, file_key: &str) -> CustomResult<Vec<u8>, FileStorageError>;
+
+ /// Begins a multipart upload, returning the identifier every subsequent part must carry.
+ async fn create_multipart_upload(
+ &self,
+ file_key: &str,
+ ) -> CustomResult<String, FileStorageError>;
+
+ /// Uploads one part of an in-progress multipart upload, returning that part's entity tag.
+ /// Part numbers start at 1. Every part except the last must be at least 5 MB.
+ async fn upload_part(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ part_number: i32,
+ body: Vec<u8>,
+ ) -> CustomResult<String, FileStorageError>;
+
+ /// Assembles the uploaded parts into a single object, returning the backend's expiry
+ /// description when a lifecycle rule applies.
+ async fn complete_multipart_upload(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ parts: Vec<(i32, String)>,
+ ) -> CustomResult<Option<String>, FileStorageError>;
+
+ /// Discards an in-progress multipart upload. Its parts are billed until this is called.
+ async fn abort_multipart_upload(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ ) -> CustomResult<(), FileStorageError>;
+
+ /// Returns a time-limited URL granting read access to the file without further authentication.
+ async fn get_presigned_download_url(
+ &self,
+ file_key: &str,
+ expires_in: std::time::Duration,
+ download_file_name: Option<&str>,
+ ) -> CustomResult<url::Url, FileStorageError>;
}
dyn_clone::clone_trait_object!(FileStorageInterface);
@@ -94,4 +134,28 @@ pub enum FileStorageError {
/// Indicates that the file deletion operation failed.
#[error("Failed to delete file")]
DeleteFailed,
+
+ /// Indicates that starting a multipart upload failed.
+ #[error("Failed to create multipart upload")]
+ MultipartCreateFailed,
+
+ /// Indicates that uploading a part of a multipart upload failed.
+ #[error("Failed to upload multipart part")]
+ MultipartUploadPartFailed,
+
+ /// Indicates that assembling a multipart upload failed.
+ #[error("Failed to complete multipart upload")]
+ MultipartCompleteFailed,
+
+ /// Indicates that discarding an in-progress multipart upload failed.
+ #[error("Failed to abort multipart upload")]
+ MultipartAbortFailed,
+
+ /// Indicates that generating a presigned URL failed.
+ #[error("Failed to generate presigned URL")]
+ PresignFailed,
+
+ /// Indicates the configured backend cannot issue presigned URLs.
+ #[error("Presigned URLs are not supported by the configured file storage backend")]
+ PresigningNotSupported,
}
diff --git a/crates/external_services/src/file_storage/aws_s3.rs b/crates/external_services/src/file_storage/aws_s3.rs
index 28d307da33..2e13be51e1 100644
--- a/crates/external_services/src/file_storage/aws_s3.rs
+++ b/crates/external_services/src/file_storage/aws_s3.rs
@@ -1,8 +1,13 @@
use aws_config::meta::region::RegionProviderChain;
use aws_sdk_s3::{
operation::{
- delete_object::DeleteObjectError, get_object::GetObjectError, put_object::PutObjectError,
+ abort_multipart_upload::AbortMultipartUploadError,
+ complete_multipart_upload::CompleteMultipartUploadError,
+ create_multipart_upload::CreateMultipartUploadError, delete_object::DeleteObjectError,
+ get_object::GetObjectError, put_object::PutObjectError, upload_part::UploadPartError,
},
+ presigning::{PresigningConfig, PresigningConfigError},
+ types::{CompletedMultipartUpload, CompletedPart},
Client,
};
use aws_sdk_sts::config::Region;
@@ -104,6 +109,128 @@ impl AwsFileStorageClient {
.map_err(AwsS3StorageError::UnknownError)?
.to_vec())
}
+
+ /// Begins a multipart upload on AWS S3.
+ async fn create_multipart_upload(
+ &self,
+ file_key: &str,
+ ) -> CustomResult<String, AwsS3StorageError> {
+ self.inner_client
+ .create_multipart_upload()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .content_type("text/csv")
+ .send()
+ .await
+ .map_err(AwsS3StorageError::MultipartCreateFailure)?
+ .upload_id
+ .ok_or_else(|| error_stack::report!(AwsS3StorageError::MissingUploadId))
+ }
+
+ /// Uploads a single part of an in-progress multipart upload to AWS S3.
+ async fn upload_part(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ part_number: i32,
+ body: Vec<u8>,
+ ) -> CustomResult<String, AwsS3StorageError> {
+ self.inner_client
+ .upload_part()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .upload_id(upload_id)
+ .part_number(part_number)
+ .body(body.into())
+ .send()
+ .await
+ .map_err(AwsS3StorageError::MultipartUploadPartFailure)?
+ .e_tag
+ .ok_or_else(|| error_stack::report!(AwsS3StorageError::MissingPartETag))
+ }
+
+ /// Assembles the uploaded parts into a single S3 object, in part number order.
+ async fn complete_multipart_upload(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ parts: Vec<(i32, String)>,
+ ) -> CustomResult<Option<String>, AwsS3StorageError> {
+ let completed_parts = parts
+ .into_iter()
+ .map(|(part_number, e_tag)| {
+ CompletedPart::builder()
+ .part_number(part_number)
+ .e_tag(e_tag)
+ .build()
+ })
+ .collect();
+
+ Ok(self
+ .inner_client
+ .complete_multipart_upload()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .upload_id(upload_id)
+ .multipart_upload(
+ CompletedMultipartUpload::builder()
+ .set_parts(Some(completed_parts))
+ .build(),
+ )
+ .send()
+ .await
+ .map_err(AwsS3StorageError::MultipartCompleteFailure)?
+ .expiration)
+ }
+
+ /// Discards an in-progress multipart upload and the parts already uploaded for it.
+ async fn abort_multipart_upload(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ ) -> CustomResult<(), AwsS3StorageError> {
+ self.inner_client
+ .abort_multipart_upload()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .upload_id(upload_id)
+ .send()
+ .await
+ .map_err(AwsS3StorageError::MultipartAbortFailure)?;
+ Ok(())
+ }
+
+ /// Signs a time-limited GET for the object with the client's current credentials.
+ async fn get_presigned_download_url(
+ &self,
+ file_key: &str,
+ expires_in: std::time::Duration,
+ download_file_name: Option<&str>,
+ ) -> CustomResult<url::Url, AwsS3StorageError> {
+ let presigning_config = PresigningConfig::expires_in(expires_in)
+ .map_err(AwsS3StorageError::PresigningConfigFailure)?;
+
+ let request = self
+ .inner_client
+ .get_object()
+ .bucket(&self.bucket_name)
+ .key(file_key)
+ .response_content_type("text/csv");
+
+ let request = match download_file_name {
+ Some(name) => {
+ request.response_content_disposition(format!("attachment; filename=\"{name}\""))
+ }
+ None => request,
+ };
+
+ let presigned = request
+ .presigned(presigning_config)
+ .await
+ .map_err(AwsS3StorageError::PresignFailure)?;
+
+ url::Url::parse(presigned.uri()).change_context(AwsS3StorageError::PresignedUrlParseFailure)
+ }
}
#[async_trait::async_trait]
@@ -135,6 +262,69 @@ impl FileStorageInterface for AwsFileStorageClient {
.await
.change_context(FileStorageError::RetrieveFailed)?)
}
+
+ /// Begins a multipart upload on AWS S3.
+ async fn create_multipart_upload(
+ &self,
+ file_key: &str,
+ ) -> CustomResult<String, FileStorageError> {
+ Ok(self
+ .create_multipart_upload(file_key)
+ .await
+ .change_context(FileStorageError::MultipartCreateFailed)?)
+ }
+
+ /// Uploads a single part of an in-progress multipart upload to AWS S3.
+ async fn upload_part(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ part_number: i32,
+ body: Vec<u8>,
+ ) -> CustomResult<String, FileStorageError> {
+ Ok(self
+ .upload_part(file_key, upload_id, part_number, body)
+ .await
+ .change_context(FileStorageError::MultipartUploadPartFailed)?)
+ }
+
+ /// Assembles the uploaded parts into a single S3 object.
+ async fn complete_multipart_upload(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ parts: Vec<(i32, String)>,
+ ) -> CustomResult<Option<String>, FileStorageError> {
+ Ok(self
+ .complete_multipart_upload(file_key, upload_id, parts)
+ .await
+ .change_context(FileStorageError::MultipartCompleteFailed)?)
+ }
+
+ /// Discards an in-progress multipart upload on AWS S3.
+ async fn abort_multipart_upload(
+ &self,
+ file_key: &str,
+ upload_id: &str,
+ ) -> CustomResult<(), FileStorageError> {
+ self.abort_multipart_upload(file_key, upload_id)
+ .await
+ .change_context(FileStorageError::MultipartAbortFailed)?;
+ Ok(())
+ }
+
+ /// Signs a time-limited GET for an object in AWS S3.
+ async fn get_presigned_download_url(
+ &self,
+ file_key: &str,
+ expires_in: std::time::Duration,
+ download_file_name: Option<&str>,
+ ) -> CustomResult<url::Url, FileStorageError> {
+ Ok(self
+ .get_presigned_download_url(file_key, expires_in, download_file_name)
+ .await
+ .change_context(FileStorageError::PresignFailed)?)
+ }
}
/// Enum representing errors that can occur during AWS S3 file storage operations.
@@ -155,4 +345,40 @@ enum AwsS3StorageError {
/// Unknown error occurred.
#[error("Unknown error occurred: {0:?}")]
UnknownError(aws_sdk_s3::primitives::ByteStreamError),
+
+ /// Error indicating that starting a multipart upload on S3 failed.
+ #[error("Multipart upload create on S3 failed: {0:?}")]
+ MultipartCreateFailure(aws_sdk_s3::error::SdkError<CreateMultipartUploadError>),
+
+ /// Error indicating that uploading a part to S3 failed.
+ #[error("Multipart part upload to S3 failed: {0:?}")]
+ MultipartUploadPartFailure(aws_sdk_s3::error::SdkError<UploadPartError>),
+
+ /// Error indicating that assembling a multipart upload on S3 failed.
+ #[error("Multipart upload complete on S3 failed: {0:?}")]
+ MultipartCompleteFailure(aws_sdk_s3::error::SdkError<CompleteMultipartUploadError>),
+
+ /// Error indicating that discarding a multipart upload on S3 failed.
+ #[error("Multipart upload abort on S3 failed: {0:?}")]
+ MultipartAbortFailure(aws_sdk_s3::error::SdkError<AbortMultipartUploadError>),
+
+ /// Error indicating S3 accepted the multipart upload but returned no upload id.
+ #[error("S3 did not return an upload id for the multipart upload")]
+ MissingUploadId,
+
+ /// Error indicating S3 accepted the part but returned no entity tag.
+ #[error("S3 did not return an entity tag for the uploaded part")]
+ MissingPartETag,
+
+ /// Error indicating the presigning configuration was rejected by the SDK.
+ #[error("Presigning configuration was rejected: {0:?}")]
+ PresigningConfigFailure(PresigningConfigError),
+
+ /// Error indicating that presigning a GET request failed.
+ #[error("Presigning an S3 get request failed: {0:?}")]
+ PresignFailure(aws_sdk_s3::error::SdkError<GetObjectError>),
+
+ /// Error indicating the presigned URI could not be parsed as a URL.
+ #[error("Presigned URI is not a valid URL")]
+ PresignedUrlParseFailure,
}
diff --git a/crates/external_services/src/file_storage/file_system.rs b/crates/external_services/src/file_storage/file_system.rs
index 19b3185e81..7f40f466d6 100644
--- a/crates/external_services/src/file_storage/file_system.rs
+++ b/crates/external_services/src/file_storage/file_system.rs
@@ -1,7 +1,7 @@
//! Module for local file system storage operations
use std::{
- fs::{remove_file, File},
+ fs::{remove_file, File, OpenOptions},
io::{Read, Write},
path::PathBuf,
};
@@ -69,6 +69,70 @@ impl FileSystem {
.change_context(FileSystemStorageError::ReadFailure)?;
Ok(received_data)
}
+
+ /// Truncates the staging file that parts are appended to.
+ async fn create_multipart_upload(
+ &self,
+ file_key: &str,
+ ) -> CustomResult<String, FileSystemStorageError> {
+ let file_path = get_file_path(staging_key(file_key));
+
+ std::fs::create_dir_all(
+ file_path
+ .parent()
+ .ok_or(FileSystemStorageError::CreateDirFailed)
+ .attach_printable("Failed to obtain parent directory")?,
+ )
+ .change_context(FileSystemStorageError::CreateDirFailed)?;
+
+ File::create(file_path).change_context(FileSystemStorageError::CreateFailure)?;
+ Ok(file_key.to_owned())
+ }
+
+ /// Appends a part to the staging file.
+ async fn upload_part(
+ &self,
+ file_key: &str,
+ body: Vec<u8>,
+ ) -> CustomResult<(), FileSystemStorageError> {
+ let file_path = get_file_path(staging_key(file_key));
+ let mut file_handler = OpenOptions::new()
+ .append(true)
+ .open(file_path)
+ .change_context(FileSystemStorageError::FileOpenFailure)?;
+ file_handler
+ .write_all(&body)
+ .change_context(FileSystemStorageError::WriteFailure)?;
+ Ok(())
+ }
+
+ /// Moves the completed staging file into place under the real key.
+ async fn complete_multipart_upload(
+ &self,
+ file_key: &str,
+ ) -> CustomResult<(), FileSystemStorageError> {
+ std::fs::rename(
+ get_file_path(staging_key(file_key)),
+ get_file_path(file_key),
+ )
+ .change_context(FileSystemStorageError::WriteFailure)?;
+ Ok(())
+ }
+
+ /// Removes the staging file for an abandoned upload.
+ async fn abort_multipart_upload(
+ &self,
+ file_key: &str,
+ ) -> CustomResult<(), FileSystemStorageError> {
+ remove_file(get_file_path(staging_key(file_key)))
+ .change_context(FileSystemStorageError::DeleteFailure)?;
+ Ok(())
+ }
+}
+
+/// Key of the staging file that parts are appended to before the upload is completed.
+fn staging_key(file_key: &str) -> String {
+ format!("{file_key}.part")
}
#[async_trait::async_trait]
@@ -100,6 +164,69 @@ impl FileStorageInterface for FileSystem {
.await
.change_context(FileStorageError::RetrieveFailed)?)
}
+
+ /// Truncates the staging file, returning the file key as the upload identifier.
+ async fn create_multipart_upload(
+ &self,
+ file_key: &str,
+ ) -> CustomResult<String, FileStorageError> {
+ Ok(self
+ .create_multipart_upload(file_key)
+ .await
+ .change_context(FileStorageError::MultipartCreateFailed)?)
+ }
+
+ /// Appends a part to the staging file. Part numbers are ignored, since appends arrive in order.
+ async fn upload_part(
+ &self,
+ file_key: &str,
+ _upload_id: &str,
+ _part_number: i32,
+ body: Vec<u8>,
+ ) -> CustomResult<String, FileStorageError> {
+ self.upload_part(file_key, body)
+ .await
+ .change_context(FileStorageError::MultipartUploadPartFailed)?;
+ Ok(String::new())
+ }
+
+ /// Moves the staging file into place under the real key. No lifecycle rule applies locally.
+ async fn complete_multipart_upload(
+ &self,
+ file_key: &str,
+ _upload_id: &str,
+ _parts: Vec<(i32, String)>,
+ ) -> CustomResult<Option<String>, FileStorageError> {
+ self.complete_multipart_upload(file_key)
+ .await
+ .change_context(FileStorageError::MultipartCompleteFailed)?;
+ Ok(None)
+ }
+
+ /// Removes the staging file for an abandoned upload.
+ async fn abort_multipart_upload(
+ &self,
+ file_key: &str,
+ _upload_id: &str,
+ ) -> CustomResult<(), FileStorageError> {
+ self.abort_multipart_upload(file_key)
+ .await
+ .change_context(FileStorageError::MultipartAbortFailed)?;
+ Ok(())
+ }
+
+ /// A local path is neither signed nor reachable by a merchant.
+ async fn get_presigned_download_url(
+ &self,
+ _file_key: &str,
+ _expires_in: std::time::Duration,
+ _download_file_name: Option<&str>,
+ ) -> CustomResult<url::Url, FileStorageError> {
+ Err(error_stack::report!(
+ FileStorageError::PresigningNotSupported
+ ))
+ .attach_printable("The file_system storage backend cannot issue presigned URLs")
+ }
}
/// Represents an error that can occur during local file system storage operations.
diff --git a/crates/openapi/src/openapi.rs b/crates/openapi/src/openapi.rs
index 0a08779b77..f38382b990 100644
--- a/crates/openapi/src/openapi.rs
+++ b/crates/openapi/src/openapi.rs
@@ -210,6 +210,7 @@ Never share your secret api keys. Keep them guarded and secure.
routes::blocklist::upload_batch_blocklist,
routes::blocklist::get_batch_blocklist_job_status,
routes::blocklist::list_batch_blocklist_jobs,
+ routes::blocklist::create_blocklist_export,
// Routes for payouts
routes::payouts::payouts_create,
@@ -1040,7 +1041,9 @@ Never share your secret api keys. Keep them guarded and secure.
api_models::blocklist::BatchBlocklistJobStatusResponse,
api_models::blocklist::ListBatchBlocklistJobsResponse,
api_models::blocklist::BlocklistRowError,
+ api_models::blocklist::BlocklistExportResponse,
api_models::enums::BatchBlocklistJobStatus,
+ api_models::enums::BatchBlocklistJobType,
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 95db744c40..5530905518 100644
--- a/crates/openapi/src/routes/blocklist.rs
+++ b/crates/openapi/src/routes/blocklist.rs
@@ -122,6 +122,7 @@ pub async fn list_blocked_payment_methods() {}
content = String,
content_type = "multipart/form-data",
description = "A multipart/form-data request with a `file` field containing a UTF-8 CSV (max 5 MiB). \
+ The part's `filename` is recorded on the job and returned as `file_name`. \
The CSV must have a header row: `type,data,metadata`. \
`type`: one of `generic_card_bin` (6 to 10 digits), `fingerprint`. \
`metadata`: optional, `key=value` pairs separated by `;` (e.g. `reason=fraud;source=manual`). \
@@ -146,10 +147,13 @@ pub async fn upload_batch_blocklist() {}
get,
path = "/blocklist/batch/{job_id}",
params(
- ("job_id" = String, Path, description = "The job ID returned by the batch upload endpoint"),
+ ("job_id" = String, Path, description = "The job ID returned by the batch upload endpoint, \
+ or the export ID returned by `POST /blocklist/export`"),
),
responses(
- (status = 200, description = "Batch blocklist job status", body = BatchBlocklistJobStatusResponse),
+ (status = 200, description = "Batch blocklist job status. For a completed export whose file \
+ is still stored, this is where the short-lived `download_url` is issued.",
+ body = BatchBlocklistJobStatusResponse),
(status = 404, description = "Job not found"),
),
tag = "Blocklist",
@@ -164,12 +168,36 @@ pub async fn get_batch_blocklist_job_status() {}
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)"),
+ ("job_type" = Option<BatchBlocklistJobType>, Query, description = "Restricts the listing to \
+ `upload` or `export` jobs. Both 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."),
),
responses(
- (status = 200, description = "List of batch blocklist jobs", body = ListBatchBlocklistJobsResponse),
+ (status = 200, description = "List of batch blocklist jobs. Rows report `downloadable`, but \
+ never `download_url` - fetch the link from `GET /blocklist/batch/{job_id}` when the \
+ merchant asks for that specific file.", body = ListBatchBlocklistJobsResponse),
),
tag = "Blocklist",
operation_id = "List batch blocklist jobs",
security(("api_key" = []))
)]
pub async fn list_batch_blocklist_jobs() {}
+
+#[utoipa::path(
+ post,
+ path = "/blocklist/export",
+ params (
+ ("X-Profile-Id" = Option<String>, Header, description = "The business profile whose \
+ blocklist is exported. Resolution follows the same rules as blocking a single entry."),
+ ),
+ responses(
+ (status = 202, description = "Blocklist export started", body = BlocklistExportResponse),
+ (status = 400, description = "No profile could be resolved"),
+ ),
+ tag = "Blocklist",
+ operation_id = "Start a blocklist CSV export",
+ security(("api_key" = []))
+)]
+pub async fn create_blocklist_export() {}
diff --git a/crates/router/src/bin/scheduler.rs b/crates/router/src/bin/scheduler.rs
index 0da2536393..3655f9d365 100644
--- a/crates/router/src/bin/scheduler.rs
+++ b/crates/router/src/bin/scheduler.rs
@@ -411,6 +411,21 @@ impl ProcessTrackerWorkflows<routes::SessionState> for WorkflowRunner {
)
}
}
+ storage::ProcessTrackerRunner::BlocklistExportWorkflow => {
+ #[cfg(feature = "v1")]
+ {
+ Ok(Box::new(
+ workflows::blocklist_export::BlocklistExportWorkflow,
+ ))
+ }
+ #[cfg(feature = "v2")]
+ {
+ Err(error_stack::report!(ProcessTrackerError::UnexpectedFlow))
+ .attach_printable(
+ "Cannot run blocklist export workflow when v1 feature is disabled",
+ )
+ }
+ }
}
};
diff --git a/crates/router/src/core/blocklist.rs b/crates/router/src/core/blocklist.rs
index 27d5aea08b..b09e976641 100644
--- a/crates/router/src/core/blocklist.rs
+++ b/crates/router/src/core/blocklist.rs
@@ -1,4 +1,5 @@
pub mod batch;
+pub mod export;
pub mod transformers;
pub mod utils;
@@ -86,8 +87,9 @@ pub async fn upload_batch_blocklist(
platform: domain::Platform,
profile_id: Option<common_utils::id_type::ProfileId>,
csv_bytes: bytes::Bytes,
+ file_name: Option<String>,
) -> RouterResponse<api_blocklist::BatchBlocklistUploadResponse> {
- batch::initiate_batch_blocklist_upload(&state, &platform, profile_id, csv_bytes)
+ batch::initiate_batch_blocklist_upload(&state, &platform, profile_id, csv_bytes, file_name)
.await
.map(services::ApplicationResponse::Json)
}
@@ -95,11 +97,13 @@ pub async fn upload_batch_blocklist(
pub async fn get_batch_blocklist_job_status(
state: SessionState,
platform: domain::Platform,
+ profile_id: Option<common_utils::id_type::ProfileId>,
job_id: String,
) -> RouterResponse<api_blocklist::BatchBlocklistJobStatusResponse> {
batch::get_batch_blocklist_job_status(
&state,
platform.get_processor().get_account().get_id(),
+ profile_id.as_ref(),
&job_id,
)
.await
@@ -109,13 +113,25 @@ pub async fn get_batch_blocklist_job_status(
pub async fn list_batch_blocklist_jobs(
state: SessionState,
platform: domain::Platform,
+ profile_id: Option<common_utils::id_type::ProfileId>,
query: api_blocklist::ListBatchBlocklistJobsQuery,
) -> RouterResponse<api_blocklist::ListBatchBlocklistJobsResponse> {
batch::list_batch_blocklist_jobs(
&state,
platform.get_processor().get_account().get_id(),
+ profile_id.as_ref(),
query,
)
.await
.map(services::ApplicationResponse::Json)
}
+
+pub async fn create_blocklist_export(
+ state: SessionState,
+ platform: domain::Platform,
+ profile_id: Option<common_utils::id_type::ProfileId>,
+) -> RouterResponse<api_blocklist::BlocklistExportResponse> {
+ export::initiate_blocklist_export(&state, &platform, profile_id)
+ .await
+ .map(services::ApplicationResponse::Json)
+}
diff --git a/crates/router/src/core/blocklist/batch.rs b/crates/router/src/core/blocklist/batch.rs
index c0dc8bc885..26ee91254c 100644
--- a/crates/router/src/core/blocklist/batch.rs
+++ b/crates/router/src/core/blocklist/batch.rs
@@ -6,8 +6,9 @@ use error_stack::{report, ResultExt};
use futures::future;
use router_env::{instrument, tracing};
use scheduler::utils as pt_utils;
-use serde::Deserialize;
+use serde::{Deserialize, Serialize};
+use super::export;
use crate::{
core::{
errors::{self, RouterResult, StorageErrorExt},
@@ -40,8 +41,12 @@ pub(crate) struct BlocklistRow {
pub metadata: Option<serde_json::Value>,
}
-#[derive(Debug, Deserialize)]
-struct BlocklistCsvRecord {
+/// Column order of the blocklist CSV, shared by import and export.
+pub(crate) const CSV_HEADER: [&str; 3] = ["type", "data", "metadata"];
+
+/// One row of the blocklist CSV, in both directions.
+#[derive(Debug, Serialize, Deserialize)]
+pub(crate) struct BlocklistCsvRecord {
#[serde(rename = "type")]
kind: String,
data: String,
@@ -49,6 +54,26 @@ struct BlocklistCsvRecord {
metadata: Option<String>,
}
+impl BlocklistCsvRecord {
+ fn from_parsed_row(row: &BlocklistRow) -> Self {
+ Self {
+ kind: data_kind_to_csv_token(row.data_kind).to_owned(),
+ data: row.data.clone(),
+ metadata: Some(metadata_to_csv_field(row.metadata.as_ref()))
+ .filter(|metadata| !metadata.is_empty()),
+ }
+ }
+
+ pub(crate) fn from_stored_entry(entry: &storage::Blocklist) -> Self {
+ Self {
+ kind: data_kind_to_csv_token(entry.data_kind).to_owned(),
+ data: entry.fingerprint_id.clone(),
+ metadata: Some(metadata_to_csv_field(entry.metadata.as_ref()))
+ .filter(|metadata| !metadata.is_empty()),
+ }
+ }
+}
+
fn parse_metadata(s: &str) -> Option<serde_json::Value> {
let map: serde_json::Map<String, serde_json::Value> = s
.split(';')
@@ -197,49 +222,57 @@ fn parse_csv(csv_bytes: &[u8]) -> Result<Vec<BlocklistRow>, api_blocklist::Block
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>> {
+/// The CSV token for a data kind. Not identity: `fingerprint` is stored as `PaymentMethod`.
+fn data_kind_to_csv_token(data_kind: common_enums::BlocklistDataKind) -> &'static str {
+ match data_kind {
+ common_enums::BlocklistDataKind::CardBin => "card_bin",
+ common_enums::BlocklistDataKind::ExtendedCardBin => "extended_card_bin",
+ common_enums::BlocklistDataKind::GenericCardBin => "generic_card_bin",
+ common_enums::BlocklistDataKind::PaymentMethod => "fingerprint",
+ }
+}
+
+/// Flattens metadata into `key=value;key=value`. Anything not a flat object renders empty.
+fn metadata_to_csv_field(metadata: Option<&serde_json::Value>) -> String {
+ metadata
+ .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()
+}
+
+/// Serializes records into headerless CSV bytes. Shared by chunk storage and the export.
+pub(crate) fn records_to_csv_bytes(
+ records: impl IntoIterator<Item = BlocklistCsvRecord>,
+) -> 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::GenericCardBin => "generic_card_bin",
- common_enums::BlocklistDataKind::PaymentMethod => "fingerprint",
- };
+ for record in records {
writer
- .write_record([type_str, row.data.as_str(), metadata_str.as_str()])
+ .serialize(record)
.change_context(errors::ApiErrorResponse::InternalServerError)
- .attach_printable("Failed to serialize batch blocklist input chunk row")?;
+ .attach_printable("Failed to serialize blocklist CSV 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")
+ .attach_printable("Failed to finalize blocklist CSV")
}
/// Parses a stored input chunk CSV (no header) into blocklist rows.
@@ -308,6 +341,7 @@ pub async fn initiate_batch_blocklist_upload(
platform: &domain::Platform,
profile_id: Option<id_type::ProfileId>,
csv_bytes: bytes::Bytes,
+ file_name: Option<String>,
) -> RouterResult<api_blocklist::BatchBlocklistUploadResponse> {
let processor_merchant_id = platform.get_processor().get_account().get_id();
let profile_id = core_utils::get_profile_id_from_business_details(
@@ -358,7 +392,9 @@ pub async fn initiate_batch_blocklist_upload(
let fs = state.file_storage_client.clone();
async move {
let key = key?;
- let chunk_bytes = rows_to_csv_bytes(chunk_rows)?;
+ let chunk_bytes = records_to_csv_bytes(
+ chunk_rows.iter().map(BlocklistCsvRecord::from_parsed_row),
+ )?;
fs.upload_file(&key, chunk_bytes)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -393,6 +429,8 @@ pub async fn initiate_batch_blocklist_upload(
created_at: now,
updated_at: now,
profile_id: profile_id.clone(),
+ job_type: common_enums::BatchBlocklistJobType::Upload,
+ file_name,
};
state
@@ -495,11 +533,11 @@ pub(crate) async fn process_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,
+ profile_id: Option<&id_type::ProfileId>,
job_id: &str,
) -> RouterResult<api_blocklist::BatchBlocklistJobStatusResponse> {
let job = state
@@ -510,9 +548,43 @@ pub async fn get_batch_blocklist_job_status(
message: format!("Batch blocklist job `{job_id}` not found"),
})?;
+ // Same scope as the listing: another profile's job is not visible from this one.
+ let job = Some(job)
+ .filter(|job| {
+ profile_id.is_none_or(|requested| {
+ job.profile_id
+ .as_ref()
+ .is_none_or(|owner| owner == requested)
+ })
+ })
+ .ok_or(errors::ApiErrorResponse::GenericNotFoundError {
+ message: format!("Batch blocklist job `{job_id}` not found"),
+ })?;
+
+ // The one place a link is minted: the merchant asked for this specific job.
+ let (download_url, download_url_expires_at) =
+ export::presign_export_download(state, &job).await.unzip();
+
+ Ok(api_blocklist::BatchBlocklistJobStatusResponse {
+ download_url,
+ download_url_expires_at,
+ ..to_job_status_response(job)?
+ })
+}
+
+/// Renders one job row, without a download link.
+fn to_job_status_response(
+ job: storage::BatchBlocklistJob,
+) -> RouterResult<api_blocklist::BatchBlocklistJobStatusResponse> {
+ let downloadable = export::is_export_downloadable(&job);
+
Ok(api_blocklist::BatchBlocklistJobStatusResponse {
job_id: job.id,
merchant_id: job.merchant_id.get_string_repr().to_owned(),
+ job_type: job
+ .job_type
+ .unwrap_or(common_enums::BatchBlocklistJobType::Upload),
+ file_name: job.file_name,
status: job.status,
total_rows: u32::try_from(job.total_rows)
.change_context(errors::ApiErrorResponse::InternalServerError)?,
@@ -522,6 +594,11 @@ pub async fn get_batch_blocklist_job_status(
.change_context(errors::ApiErrorResponse::InternalServerError)?,
created_at: job.created_at,
updated_at: job.updated_at,
+ expires_at: job.expires_at,
+ downloadable,
+ error_message: job.error_message,
+ download_url: None,
+ download_url_expires_at: None,
})
}
@@ -530,20 +607,27 @@ pub async fn get_batch_blocklist_job_status(
pub async fn list_batch_blocklist_jobs(
state: &SessionState,
merchant_id: &id_type::MerchantId,
+ profile_id: Option<&id_type::ProfileId>,
query: api_blocklist::ListBatchBlocklistJobsQuery,
) -> RouterResult<api_blocklist::ListBatchBlocklistJobsResponse> {
- let limit = i64::from(query.limit.get());
- let offset = i64::from(query.offset.get());
+ let limit = query.limit.as_i64();
+ let offset = query.offset.as_i64();
+ // The page and the total have to use the same filter or they contradict each other.
+ let job_type = query.job_type;
let (jobs, total_count) = future::try_join(
state.store.list_batch_blocklist_jobs_by_merchant_id(
merchant_id.get_string_repr(),
+ profile_id,
+ job_type,
limit,
offset,
),
- state
- .store
- .count_batch_blocklist_jobs_by_merchant_id(merchant_id.get_string_repr()),
+ state.store.count_batch_blocklist_jobs_by_merchant_id(
+ merchant_id.get_string_repr(),
+ profile_id,
+ job_type,
+ ),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
@@ -552,21 +636,7 @@ pub async fn 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,
- })
- })
+ .map(to_job_status_response)
.collect::<RouterResult<Vec<_>>>()?;
Ok(api_blocklist::ListBatchBlocklistJobsResponse {
diff --git a/crates/router/src/core/blocklist/export.rs b/crates/router/src/core/blocklist/export.rs
new file mode 100644
index 0000000000..27b4390602
--- /dev/null
+++ b/crates/router/src/core/blocklist/export.rs
@@ -0,0 +1,209 @@
+//! Blocklist CSV export helpers.
+use api_models::blocklist as api_blocklist;
+use common_utils::{date_time, id_type};
+use csv::WriterBuilder;
+use error_stack::ResultExt;
+use router_env::{instrument, tracing};
+use scheduler::utils as pt_utils;
+
+use super::batch;
+use crate::{
+ core::{
+ errors::{self, RouterResult, StorageErrorExt},
+ utils as core_utils,
+ },
+ logger,
+ routes::SessionState,
+ types::{domain, storage},
+};
+
+const BLOCKLIST_EXPORT_TASK: &str = "BLOCKLIST_EXPORT";
+const BLOCKLIST_EXPORT_TAGS: [&str; 2] = ["BLOCKLIST", "EXPORT"];
+
+pub(crate) const EXPORT_PAGE_SIZE: i64 = 5_000;
+
+/// S3 requires every part except the last to be at least 5 MB.
+pub(crate) const MULTIPART_PART_SIZE: usize = 5 * 1024 * 1024;
+
+/// Lifetime of a generated download link. Kept short because the credentials signing it rotate.
+const PRESIGNED_URL_TTL: time::Duration = time::Duration::seconds(900);
+
+/// Dated so repeated exports do not overwrite each other in a downloads folder.
+fn export_file_name(created_at: time::PrimitiveDateTime) -> String {
+ format!(
+ "blocklist_export_{:04}{:02}{:02}_{:02}{:02}{:02}.csv",
+ created_at.year(),
+ u8::from(created_at.month()),
+ created_at.day(),
+ created_at.hour(),
+ created_at.minute(),
+ created_at.second(),
+ )
+}
+
+pub(crate) fn export_key(merchant_id: &str, profile_id: &str, export_id: &str) -> String {
+ format!("blocklist/export/{merchant_id}/{profile_id}/{export_id}.csv")
+}
+
+/// The header row, matching what `POST /blocklist/batch` accepts.
+pub(crate) fn csv_header() -> RouterResult<Vec<u8>> {
+ let mut writer = WriterBuilder::new()
+ .has_headers(false)
+ .from_writer(Vec::new());
+ writer
+ .write_record(batch::CSV_HEADER)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to write blocklist export CSV header")?;
+ writer
+ .into_inner()
+ .map_err(|error| error.into_error())
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to finalize blocklist export CSV header")
+}
+
+/// Serializes one page of blocklist entries into CSV.
+pub(crate) fn rows_to_csv_bytes(rows: &[storage::Blocklist]) -> RouterResult<Vec<u8>> {
+ batch::records_to_csv_bytes(
+ rows.iter()
+ .map(batch::BlocklistCsvRecord::from_stored_entry),
+ )
+}
+
+#[instrument(skip_all, fields(flow = ?router_env::Flow::CreateBlocklistExport))]
+pub async fn initiate_blocklist_export(
+ state: &SessionState,
+ platform: &domain::Platform,
+ profile_id: Option<id_type::ProfileId>,
+) -> RouterResult<api_blocklist::BlocklistExportResponse> {
+ let processor_merchant_id = platform.get_processor().get_account().get_id();
+ let profile_id = core_utils::get_profile_id_from_business_details(
+ None,
+ None,
+ platform.get_processor(),
+ profile_id.as_ref(),
+ &*state.store,
+ true,
+ )
+ .await?;
+
+ let export_id = common_utils::generate_id(crate::consts::ID_LENGTH, "blkexp");
+ let now = date_time::now();
+ let file_name = export_file_name(now);
+
+ let job_new = storage::BatchBlocklistJobNew {
+ id: export_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: profile_id.clone(),
+ job_type: common_enums::BatchBlocklistJobType::Export,
+ file_name: Some(file_name.clone()),
+ };
+
+ state
+ .store
+ .insert_batch_blocklist_job(job_new)
+ .await
+ .to_duplicate_response(errors::ApiErrorResponse::InternalServerError)?;
+
+ let tracking_data = storage::BlocklistExportTrackingData {
+ job_id: export_id.clone(),
+ merchant_id: platform.get_provider().get_account().get_id().clone(),
+ processor_merchant_id: Some(processor_merchant_id.clone()),
+ profile_id,
+ snapshot_at: now,
+ upload_id: None,
+ };
+
+ let runner = storage::ProcessTrackerRunner::BlocklistExportWorkflow;
+ let process_tracker_id = pt_utils::get_process_tracker_id(
+ runner,
+ BLOCKLIST_EXPORT_TASK,
+ &export_id,
+ processor_merchant_id,
+ );
+
+ let process_tracker_entry = storage::ProcessTrackerNew::new(
+ process_tracker_id,
+ BLOCKLIST_EXPORT_TASK,
+ runner,
+ BLOCKLIST_EXPORT_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 blocklist export job")?;
+
+ state
+ .store
+ .insert_process(process_tracker_entry)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to enqueue blocklist export ProcessTracker task")?;
+
+ logger::info!(export_id = %export_id, "Blocklist export job initiated");
+
+ Ok(api_blocklist::BlocklistExportResponse {
+ export_id,
+ status: common_enums::BatchBlocklistJobStatus::Initiated,
+ file_name,
+ })
+}
+
+/// Shared by the listing's `downloadable` flag and the signing path, so the two cannot disagree.
+pub(crate) fn is_export_downloadable(job: &storage::BatchBlocklistJob) -> bool {
+ matches!(
+ job.job_type,
+ Some(common_enums::BatchBlocklistJobType::Export)
+ ) && matches!(job.status, common_enums::BatchBlocklistJobStatus::Completed)
+ && job.file_key.is_some()
+ && job
+ .expires_at
+ .is_none_or(|expires_at| expires_at > date_time::now())
+}
+
+/// Logs rather than propagating when the storage backend cannot sign.
+pub(crate) async fn presign_export_download(
+ state: &SessionState,
+ job: &storage::BatchBlocklistJob,
+) -> Option<(
+ hyperswitch_masking::Secret<url::Url>,
+ time::PrimitiveDateTime,
+)> {
+ match job
+ .file_key
+ .as_ref()
+ .filter(|_| is_export_downloadable(job))
+ {
+ Some(file_key) => state
+ .file_storage_client
+ .get_presigned_download_url(
+ file_key,
+ PRESIGNED_URL_TTL.unsigned_abs(),
+ job.file_name.as_deref(),
+ )
+ .await
+ .inspect_err(|error| {
+ logger::warn!(
+ ?error,
+ export_id = %job.id,
+ "Failed to sign a blocklist export download URL"
+ );
+ })
+ .ok()
+ .map(|url| {
+ (
+ hyperswitch_masking::Secret::new(url),
+ date_time::now().saturating_add(PRESIGNED_URL_TTL),
+ )
+ }),
+ None => None,
+ }
+}
diff --git a/crates/router/src/db/batch_blocklist_job.rs b/crates/router/src/db/batch_blocklist_job.rs
index a8177f6202..289fdc6b8c 100644
--- a/crates/router/src/db/batch_blocklist_job.rs
+++ b/crates/router/src/db/batch_blocklist_job.rs
@@ -10,6 +10,22 @@ use crate::{
types::storage,
};
+/// The listing predicate the SQL queries apply, restated for `MockDb` so the two agree.
+fn matches_job_scope(
+ job: &storage::BatchBlocklistJob,
+ merchant_id: &str,
+ profile_id: Option<&common_utils::id_type::ProfileId>,
+ job_type: Option<common_enums::BatchBlocklistJobType>,
+) -> bool {
+ job.merchant_id.get_string_repr() == merchant_id
+ && job_type.is_none_or(|job_type| job.job_type == Some(job_type))
+ && profile_id.is_none_or(|profile_id| {
+ job.profile_id
+ .as_ref()
+ .is_none_or(|job_profile_id| job_profile_id == profile_id)
+ })
+}
+
#[async_trait::async_trait]
pub trait BatchBlocklistJobInterface {
async fn insert_batch_blocklist_job(
@@ -23,9 +39,12 @@ pub trait BatchBlocklistJobInterface {
merchant_id: &str,
) -> CustomResult<storage::BatchBlocklistJob, errors::StorageError>;
+ /// `profile_id` restricts the page to that profile; `None` lists the whole merchant.
async fn list_batch_blocklist_jobs_by_merchant_id(
&self,
merchant_id: &str,
+ profile_id: Option<&common_utils::id_type::ProfileId>,
+ job_type: Option<common_enums::BatchBlocklistJobType>,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::BatchBlocklistJob>, errors::StorageError>;
@@ -40,6 +59,8 @@ pub trait BatchBlocklistJobInterface {
async fn count_batch_blocklist_jobs_by_merchant_id(
&self,
merchant_id: &str,
+ profile_id: Option<&common_utils::id_type::ProfileId>,
+ job_type: Option<common_enums::BatchBlocklistJobType>,
) -> CustomResult<usize, errors::StorageError>;
}
@@ -72,13 +93,50 @@ impl BatchBlocklistJobInterface for Store {
async fn list_batch_blocklist_jobs_by_merchant_id(
&self,
merchant_id: &str,
+ profile_id: Option<&common_utils::id_type::ProfileId>,
+ job_type: Option<common_enums::BatchBlocklistJobType>,
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)))
+ match (profile_id, job_type) {
+ (Some(profile_id), Some(job_type)) => {
+ storage::BatchBlocklistJob::list_by_merchant_id_profile_id_job_type(
+ &conn,
+ merchant_id,
+ profile_id,
+ job_type,
+ limit,
+ offset,
+ )
+ .await
+ }
+ (Some(profile_id), None) => {
+ storage::BatchBlocklistJob::list_by_merchant_id_profile_id(
+ &conn,
+ merchant_id,
+ profile_id,
+ limit,
+ offset,
+ )
+ .await
+ }
+ (None, Some(job_type)) => {
+ storage::BatchBlocklistJob::list_by_merchant_id_job_type(
+ &conn,
+ merchant_id,
+ job_type,
+ limit,
+ offset,
+ )
+ .await
+ }
+ (None, None) => {
+ storage::BatchBlocklistJob::list_by_merchant_id(&conn, merchant_id, limit, offset)
+ .await
+ }
+ }
+ .map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
@@ -98,11 +156,41 @@ impl BatchBlocklistJobInterface for Store {
async fn count_batch_blocklist_jobs_by_merchant_id(
&self,
merchant_id: &str,
+ profile_id: Option<&common_utils::id_type::ProfileId>,
+ job_type: Option<common_enums::BatchBlocklistJobType>,
) -> 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)))
+ match (profile_id, job_type) {
+ (Some(profile_id), Some(job_type)) => {
+ storage::BatchBlocklistJob::count_by_merchant_id_profile_id_job_type(
+ &conn,
+ merchant_id,
+ profile_id,
+ job_type,
+ )
+ .await
+ }
+ (Some(profile_id), None) => {
+ storage::BatchBlocklistJob::count_by_merchant_id_profile_id(
+ &conn,
+ merchant_id,
+ profile_id,
+ )
+ .await
+ }
+ (None, Some(job_type)) => {
+ storage::BatchBlocklistJob::count_by_merchant_id_job_type(
+ &conn,
+ merchant_id,
+ job_type,
+ )
+ .await
+ }
+ (None, None) => {
+ storage::BatchBlocklistJob::count_by_merchant_id(&conn, merchant_id).await
+ }
+ }
+ .map_err(|error| report!(errors::StorageError::from(error)))
}
}
@@ -127,6 +215,11 @@ impl BatchBlocklistJobInterface for MockDb {
created_at: new.created_at,
updated_at: new.updated_at,
profile_id: Some(new.profile_id),
+ job_type: Some(new.job_type),
+ file_name: new.file_name,
+ file_key: None,
+ error_message: None,
+ expires_at: None,
};
jobs.push(job.clone());
Ok(job)
@@ -156,6 +249,8 @@ impl BatchBlocklistJobInterface for MockDb {
async fn list_batch_blocklist_jobs_by_merchant_id(
&self,
merchant_id: &str,
+ profile_id: Option<&common_utils::id_type::ProfileId>,
+ job_type: Option<common_enums::BatchBlocklistJobType>,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::BatchBlocklistJob>, errors::StorageError> {
@@ -164,7 +259,7 @@ impl BatchBlocklistJobInterface for MockDb {
.lock()
.await
.iter()
- .filter(|j| j.merchant_id.get_string_repr() == merchant_id)
+ .filter(|j| matches_job_scope(j, merchant_id, profile_id, job_type))
.cloned()
.collect::<Vec<_>>()
.into_iter()
@@ -196,6 +291,18 @@ impl BatchBlocklistJobInterface for MockDb {
if let Some(failed_rows) = update.failed_rows {
job.failed_rows = failed_rows;
}
+ if let Some(total_rows) = update.total_rows {
+ job.total_rows = total_rows;
+ }
+ if let Some(file_key) = update.file_key {
+ job.file_key = Some(file_key);
+ }
+ if let Some(error_message) = update.error_message {
+ job.error_message = Some(error_message);
+ }
+ if let Some(expires_at) = update.expires_at {
+ job.expires_at = Some(expires_at);
+ }
job.updated_at = update.updated_at;
Ok(job.clone())
}
@@ -204,13 +311,15 @@ impl BatchBlocklistJobInterface for MockDb {
async fn count_batch_blocklist_jobs_by_merchant_id(
&self,
merchant_id: &str,
+ profile_id: Option<&common_utils::id_type::ProfileId>,
+ job_type: Option<common_enums::BatchBlocklistJobType>,
) -> CustomResult<usize, errors::StorageError> {
Ok(self
.batch_blocklist_jobs
.lock()
.await
.iter()
- .filter(|j| j.merchant_id.get_string_repr() == merchant_id)
+ .filter(|j| matches_job_scope(j, merchant_id, profile_id, job_type))
.count())
}
}
@@ -240,11 +349,19 @@ impl BatchBlocklistJobInterface for KafkaStore {
async fn list_batch_blocklist_jobs_by_merchant_id(
&self,
merchant_id: &str,
+ profile_id: Option<&common_utils::id_type::ProfileId>,
+ job_type: Option<common_enums::BatchBlocklistJobType>,
limit: i64,
offset: i64,
) -> CustomResult<Vec<storage::BatchBlocklistJob>, errors::StorageError> {
self.diesel_store
- .list_batch_blocklist_jobs_by_merchant_id(merchant_id, limit, offset)
+ .list_batch_blocklist_jobs_by_merchant_id(
+ merchant_id,
+ profile_id,
+ job_type,
+ limit,
+ offset,
+ )
.await
}
@@ -264,9 +381,11 @@ impl BatchBlocklistJobInterface for KafkaStore {
async fn count_batch_blocklist_jobs_by_merchant_id(
&self,
merchant_id: &str,
+ profile_id: Option<&common_utils::id_type::ProfileId>,
+ job_type: Option<common_enums::BatchBlocklistJobType>,
) -> CustomResult<usize, errors::StorageError> {
self.diesel_store
- .count_batch_blocklist_jobs_by_merchant_id(merchant_id)
+ .count_batch_blocklist_jobs_by_merchant_id(merchant_id, profile_id, job_type)
.await
}
}
diff --git a/crates/router/src/db/blocklist.rs b/crates/router/src/db/blocklist.rs
index 88302afaef..a28cdb562a 100644
--- a/crates/router/src/db/blocklist.rs
+++ b/crates/router/src/db/blocklist.rs
@@ -1,6 +1,6 @@
use error_stack::{report, ResultExt};
use router_env::{instrument, tracing};
-use storage_impl::MockDb;
+use storage_impl::{utils::pg_connection_read_replica, MockDb};
use super::Store;
use crate::{
@@ -72,6 +72,26 @@ pub trait BlocklistInterface {
offset: i64,
) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;
+ /// `""` reads from the beginning; `snapshot_at` excludes anything blocked after it.
+ async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(
+ &self,
+ processor_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;
+
+ /// The same page over rows written before `processor_merchant_id` existed.
+ async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError>;
+
async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(
&self,
processor_merchant_id: &common_utils::id_type::MerchantId,
@@ -405,6 +425,50 @@ impl BlocklistInterface for Store {
)))
}
+ #[instrument(skip_all)]
+ async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(
+ &self,
+ processor_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
+ let conn = pg_connection_read_replica(self).await?;
+ storage::Blocklist::list_after_fingerprint_by_processor_merchant_id_profile_id(
+ &conn,
+ processor_merchant_id,
+ profile_id,
+ after_fingerprint_id,
+ snapshot_at,
+ limit,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
+ #[instrument(skip_all)]
+ async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
+ let conn = pg_connection_read_replica(self).await?;
+ storage::Blocklist::list_after_fingerprint_by_legacy_merchant_id_profile_id(
+ &conn,
+ merchant_id,
+ profile_id,
+ after_fingerprint_id,
+ snapshot_at,
+ limit,
+ )
+ .await
+ .map_err(|error| report!(errors::StorageError::from(error)))
+ }
+
#[instrument(skip_all)]
async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(
&self,
@@ -567,6 +631,59 @@ impl BlocklistInterface for MockDb {
Err(errors::StorageError::MockDbError)?
}
+ async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(
+ &self,
+ processor_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
+ let mut entries = self
+ .blocklists
+ .lock()
+ .await
+ .iter()
+ .filter(|entry| {
+ entry.processor_merchant_id.as_ref() == Some(processor_merchant_id)
+ && entry.fingerprint_id > after_fingerprint_id
+ && entry.created_at <= snapshot_at
+ && (entry.profile_id.as_ref() == Some(profile_id) || entry.profile_id.is_none())
+ })
+ .cloned()
+ .collect::<Vec<_>>();
+ entries.sort_by(|left, right| left.fingerprint_id.cmp(&right.fingerprint_id));
+ entries.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
+ Ok(entries)
+ }
+
+ async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
+ let mut entries = self
+ .blocklists
+ .lock()
+ .await
+ .iter()
+ .filter(|entry| {
+ entry.merchant_id == *merchant_id
+ && entry.processor_merchant_id.is_none()
+ && entry.fingerprint_id > after_fingerprint_id
+ && entry.created_at <= snapshot_at
+ && (entry.profile_id.as_ref() == Some(profile_id) || entry.profile_id.is_none())
+ })
+ .cloned()
+ .collect::<Vec<_>>();
+ entries.sort_by(|left, right| left.fingerprint_id.cmp(&right.fingerprint_id));
+ entries.truncate(usize::try_from(limit).unwrap_or(usize::MAX));
+ Ok(entries)
+ }
+
async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(
&self,
_processor_merchant_id: &common_utils::id_type::MerchantId,
@@ -755,6 +872,46 @@ impl BlocklistInterface for KafkaStore {
.await
}
+ #[instrument(skip_all)]
+ async fn list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(
+ &self,
+ processor_merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
+ self.diesel_store
+ .list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(
+ processor_merchant_id,
+ profile_id,
+ after_fingerprint_id,
+ snapshot_at,
+ limit,
+ )
+ .await
+ }
+
+ #[instrument(skip_all)]
+ async fn list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(
+ &self,
+ merchant_id: &common_utils::id_type::MerchantId,
+ profile_id: &common_utils::id_type::ProfileId,
+ after_fingerprint_id: String,
+ snapshot_at: time::PrimitiveDateTime,
+ limit: i64,
+ ) -> CustomResult<Vec<storage::Blocklist>, errors::StorageError> {
+ self.diesel_store
+ .list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(
+ merchant_id,
+ profile_id,
+ after_fingerprint_id,
+ snapshot_at,
+ limit,
+ )
+ .await
+ }
+
#[instrument(skip_all)]
async fn get_blocklist_entries_count_by_processor_merchant_id_profile_id_data_kind(
&self,
diff --git a/crates/router/src/routes/app.rs b/crates/router/src/routes/app.rs
index 14d805cf8d..7176686789 100644
--- a/crates/router/src/routes/app.rs
+++ b/crates/router/src/routes/app.rs
@@ -1997,6 +1997,9 @@ impl Blocklist {
web::resource("/batch/{job_id}")
.route(web::get().to(blocklist::get_batch_blocklist_job_status)),
)
+ .service(
+ web::resource("/export").route(web::post().to(blocklist::create_blocklist_export)),
+ )
}
}
diff --git a/crates/router/src/routes/blocklist.rs b/crates/router/src/routes/blocklist.rs
index 9d6854641b..fbbd340621 100644
--- a/crates/router/src/routes/blocklist.rs
+++ b/crates/router/src/routes/blocklist.rs
@@ -384,6 +384,7 @@ pub async fn upload_batch_blocklist(
) -> HttpResponse {
let flow = Flow::BatchBlocklistUpload;
let csv_bytes = bytes::Bytes::from(form.file.data.to_vec());
+ let file_name = form.file.file_name.clone();
Box::pin(api::server_wrap(
flow,
@@ -392,9 +393,17 @@ pub async fn upload_batch_blocklist(
(),
|state, auth: auth::AuthenticationData, _payload, _| {
let csv_bytes = csv_bytes.clone();
+ let file_name = file_name.clone();
let profile_id = auth.profile.map(|profile| profile.get_id().clone());
async move {
- blocklist::upload_batch_blocklist(state, auth.platform, profile_id, csv_bytes).await
+ blocklist::upload_batch_blocklist(
+ state,
+ auth.platform,
+ profile_id,
+ csv_bytes,
+ file_name,
+ )
+ .await
}
},
auth::auth_type(
@@ -441,7 +450,8 @@ pub async fn get_batch_blocklist_job_status(
&req,
job_id,
|state, auth: auth::AuthenticationData, job_id, _| {
- blocklist::get_batch_blocklist_job_status(state, auth.platform, job_id)
+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());
+ blocklist::get_batch_blocklist_job_status(state, auth.platform, profile_id, job_id)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
@@ -466,6 +476,11 @@ pub async fn get_batch_blocklist_job_status(
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)"),
+ ("job_type" = Option<BatchBlocklistJobType>, Query, description = "Restricts the listing to \
+ `upload` or `export` jobs. Both 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."),
),
responses(
(status = 200, description = "List of batch blocklist jobs", body = ListBatchBlocklistJobsResponse),
@@ -486,7 +501,8 @@ pub async fn list_batch_blocklist_jobs(
&req,
query_payload.into_inner(),
|state, auth: auth::AuthenticationData, query, _| {
- blocklist::list_batch_blocklist_jobs(state, auth.platform, query)
+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());
+ blocklist::list_batch_blocklist_jobs(state, auth.platform, profile_id, query)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
@@ -504,3 +520,48 @@ pub async fn list_batch_blocklist_jobs(
))
.await
}
+
+// ---- Blocklist CSV export route handlers ----
+
+#[utoipa::path(
+ post,
+ path = "/blocklist/export",
+ params (
+ ("X-Profile-Id" = Option<String>, Header, description = "The business profile whose \
+ blocklist is exported. Resolution follows the same rules as blocking a single entry."),
+ ),
+ responses(
+ (status = 202, description = "Blocklist export started", body = BlocklistExportResponse),
+ (status = 400, description = "No profile could be resolved"),
+ ),
+ tag = "Blocklist",
+ operation_id = "Start a blocklist CSV export",
+ security(("api_key" = []))
+)]
+pub async fn create_blocklist_export(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
+ let flow = Flow::CreateBlocklistExport;
+ Box::pin(api::server_wrap(
+ flow,
+ state,
+ &req,
+ (),
+ |state, auth: auth::AuthenticationData, _payload, _| {
+ let profile_id = auth.profile.map(|profile| profile.get_id().clone());
+ blocklist::create_blocklist_export(state, auth.platform, profile_id)
+ },
+ 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.rs
index 0aa7356dc6..0627b3a738 100644
--- a/crates/router/src/routes/lock_utils.rs
+++ b/crates/router/src/routes/lock_utils.rs
@@ -114,6 +114,7 @@ impl From<Flow> for ApiIdentifier {
Flow::ListBatchBlocklistJobs => Self::Blocklist,
Flow::GetBlocklistCount => Self::Blocklist,
Flow::LookupBlocklistEntry => Self::Blocklist,
+ Flow::CreateBlocklistExport => Self::Blocklist,
Flow::MerchantConnectorsCreate
| Flow::MerchantConnectorsRetrieve
| Flow::MerchantConnectorsUpdate
diff --git a/crates/router/src/types/storage/batch_blocklist_job.rs b/crates/router/src/types/storage/batch_blocklist_job.rs
index 8fc6763b03..4ad95068ff 100644
--- a/crates/router/src/types/storage/batch_blocklist_job.rs
+++ b/crates/router/src/types/storage/batch_blocklist_job.rs
@@ -13,3 +13,15 @@ pub struct BatchBlocklistTrackingData {
pub created_by: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
}
+
+#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
+pub struct BlocklistExportTrackingData {
+ pub job_id: String,
+ pub merchant_id: id_type::MerchantId,
+ pub processor_merchant_id: Option<id_type::MerchantId>,
+ pub profile_id: id_type::ProfileId,
+ /// Bounds the scan, so a run spanning minutes still describes one moment.
+ pub snapshot_at: time::PrimitiveDateTime,
+ /// Written once the multipart upload starts, so a retry can discard the abandoned parts.
+ pub upload_id: Option<String>,
+}
diff --git a/crates/router/src/workflows.rs b/crates/router/src/workflows.rs
index 89c744d6e3..e1d2981d75 100644
--- a/crates/router/src/workflows.rs
+++ b/crates/router/src/workflows.rs
@@ -31,3 +31,6 @@ pub mod network_tokenization;
#[cfg(feature = "v1")]
pub mod offer_engine_notify;
+
+#[cfg(feature = "v1")]
+pub mod blocklist_export;
diff --git a/crates/router/src/workflows/batch_blocklist_upload.rs b/crates/router/src/workflows/batch_blocklist_upload.rs
index c03dceb6f3..5387201fc5 100644
--- a/crates/router/src/workflows/batch_blocklist_upload.rs
+++ b/crates/router/src/workflows/batch_blocklist_upload.rs
@@ -100,6 +100,10 @@ async fn run_batch_job(
status: None,
succeeded_rows: Some(total_succeeded),
failed_rows: None,
+ total_rows: None,
+ file_key: None,
+ error_message: None,
+ expires_at: None,
updated_at: common_utils::date_time::now(),
},
)
@@ -178,6 +182,10 @@ impl ProcessTrackerWorkflow<SessionState> for BatchBlocklistUploadWorkflow {
status: Some(common_enums::BatchBlocklistJobStatus::Processing),
succeeded_rows: None,
failed_rows: None,
+ total_rows: None,
+ file_key: None,
+ error_message: None,
+ expires_at: None,
updated_at: common_utils::date_time::now(),
},
)
@@ -197,6 +205,10 @@ impl ProcessTrackerWorkflow<SessionState> for BatchBlocklistUploadWorkflow {
status: Some(common_enums::BatchBlocklistJobStatus::Completed),
succeeded_rows: Some(succeeded_rows),
failed_rows: Some(failed_rows),
+ total_rows: None,
+ file_key: None,
+ error_message: None,
+ expires_at: None,
updated_at: common_utils::date_time::now(),
},
)
@@ -259,6 +271,10 @@ impl ProcessTrackerWorkflow<SessionState> for BatchBlocklistUploadWorkflow {
status: Some(common_enums::BatchBlocklistJobStatus::Failed),
succeeded_rows: None,
failed_rows: Some(failed_rows),
+ total_rows: None,
+ file_key: None,
+ error_message: None,
+ expires_at: 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.rs
new file mode 100644
index 0000000000..867aba38c3
--- /dev/null
+++ b/crates/router/src/workflows/blocklist_export.rs
@@ -0,0 +1,430 @@
+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::export,
+ errors::{self, RouterResult},
+ },
+ logger::{error, info, warn},
+ routes::SessionState,
+ types::storage,
+};
+
+pub struct BlocklistExportWorkflow;
+
+struct ExportProgress {
+ row_count: usize,
+ buffer: Vec<u8>,
+ parts: Vec<(i32, String)>,
+}
+
+/// The inputs that stay fixed for one export run.
+struct ExportScope<'a> {
+ file_key: &'a str,
+ upload_id: &'a str,
+ merchant_id: &'a id_type::MerchantId,
+ profile_id: &'a id_type::ProfileId,
+ snapshot_at: time::PrimitiveDateTime,
+}
+
+async fn drain_scope(
+ state: &SessionState,
+ scope: &ExportScope<'_>,
+ legacy: bool,
+ progress: &mut ExportProgress,
+) -> RouterResult<()> {
+ // `""` sorts below every stored fingerprint, so the first page starts at the beginning.
+ let mut cursor = String::new();
+
+ loop {
+ let page =
+ match legacy {
+ false => state
+ .store
+ .list_blocklist_entries_after_fingerprint_by_processor_merchant_id_profile_id(
+ scope.merchant_id,
+ scope.profile_id,
+ cursor.clone(),
+ scope.snapshot_at,
+ export::EXPORT_PAGE_SIZE,
+ )
+ .await,
+ true => {
+ state
+ .store
+ .list_blocklist_entries_after_fingerprint_by_legacy_merchant_id_profile_id(
+ scope.merchant_id,
+ scope.profile_id,
+ cursor.clone(),
+ scope.snapshot_at,
+ export::EXPORT_PAGE_SIZE,
+ )
+ .await
+ }
+ }
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to read a blocklist page for export")?;
+
+ let next_cursor = page.last().map(|row| row.fingerprint_id.clone());
+
+ match next_cursor {
+ None => break,
+ Some(last_fingerprint) => {
+ progress.row_count += page.len();
+ progress
+ .buffer
+ .extend_from_slice(&export::rows_to_csv_bytes(&page)?);
+ cursor = last_fingerprint;
+
+ if progress.buffer.len() >= export::MULTIPART_PART_SIZE {
+ upload_buffered_part(state, scope, progress).await?;
+ }
+ }
+ }
+ }
+
+ Ok(())
+}
+
+/// Ships whatever is buffered as the next part.
+async fn upload_buffered_part(
+ state: &SessionState,
+ scope: &ExportScope<'_>,
+ progress: &mut ExportProgress,
+) -> RouterResult<()> {
+ let part_number = i32::try_from(progress.parts.len() + 1)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Blocklist export exceeded the maximum multipart part count")?;
+
+ let e_tag = state
+ .file_storage_client
+ .upload_part(
+ scope.file_key,
+ scope.upload_id,
+ part_number,
+ std::mem::take(&mut progress.buffer),
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable_lazy(|| {
+ format!("Failed to upload blocklist export part {part_number}")
+ })?;
+
+ progress.parts.push((part_number, e_tag));
+ Ok(())
+}
+
+async fn run_export_job(
+ state: &SessionState,
+ process_id: &str,
+ tracking_data: storage::BlocklistExportTrackingData,
+ merchant_id: &id_type::MerchantId,
+) -> RouterResult<(usize, Option<String>)> {
+ let file_key = export::export_key(
+ merchant_id.get_string_repr(),
+ tracking_data.profile_id.get_string_repr(),
+ &tracking_data.job_id,
+ );
+
+ // A retry inherits the previous attempt's upload. Discard it so its parts stop being billed.
+ if let Some(stale_upload_id) = tracking_data.upload_id.as_ref() {
+ if let Err(error) = state
+ .file_storage_client
+ .abort_multipart_upload(&file_key, stale_upload_id)
+ .await
+ {
+ warn!(
+ job_id = %tracking_data.job_id,
+ error = ?error,
+ "Failed to abort the previous blocklist export upload before retrying"
+ );
+ }
+ }
+
+ let upload_id = state
+ .file_storage_client
+ .create_multipart_upload(&file_key)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to start the blocklist export multipart upload")?;
+
+ persist_upload_id(state, process_id, &tracking_data, &upload_id).await?;
+
+ let scope = ExportScope {
+ file_key: &file_key,
+ upload_id: &upload_id,
+ merchant_id,
+ profile_id: &tracking_data.profile_id,
+ snapshot_at: tracking_data.snapshot_at,
+ };
+
+ let result = collect_and_complete(state, &scope).await;
+
+ match result {
+ Ok(outcome) => Ok(outcome),
+ Err(error) => {
+ if let Err(abort_error) = state
+ .file_storage_client
+ .abort_multipart_upload(&file_key, &upload_id)
+ .await
+ {
+ warn!(
+ job_id = %tracking_data.job_id,
+ error = ?abort_error,
+ "Failed to abort the blocklist export upload after a failure"
+ );
+ }
+ Err(error)
+ }
+ }
+}
+
+async fn collect_and_complete(
+ state: &SessionState,
+ scope: &ExportScope<'_>,
+) -> RouterResult<(usize, Option<String>)> {
+ let mut progress = ExportProgress {
+ row_count: 0,
+ buffer: export::csv_header()?,
+ parts: Vec::new(),
+ };
+
+ drain_scope(state, scope, false, &mut progress).await?;
+ drain_scope(state, scope, true, &mut progress).await?;
+
+ // The final part is the only one allowed below the minimum size.
+ if !progress.buffer.is_empty() {
+ upload_buffered_part(state, scope, &mut progress).await?;
+ }
+
+ let expiration = state
+ .file_storage_client
+ .complete_multipart_upload(scope.file_key, scope.upload_id, progress.parts)
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to complete the blocklist export multipart upload")?;
+
+ Ok((progress.row_count, expiration))
+}
+
+/// Records the upload id on the task so a retry can find and discard the abandoned parts.
+async fn persist_upload_id(
+ state: &SessionState,
+ process_id: &str,
+ tracking_data: &storage::BlocklistExportTrackingData,
+ upload_id: &str,
+) -> RouterResult<()> {
+ let updated = storage::BlocklistExportTrackingData {
+ upload_id: Some(upload_id.to_owned()),
+ ..tracking_data.clone()
+ };
+
+ let value = serde_json::to_value(&updated)
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to serialise blocklist export 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(value),
+ business_status: None,
+ status: None,
+ updated_at: Some(common_utils::date_time::now()),
+ },
+ )
+ .await
+ .change_context(errors::ApiErrorResponse::InternalServerError)
+ .attach_printable("Failed to record the blocklist export upload id")?;
+
+ Ok(())
+}
+
+/// Reads the expiry date out of `expiry-date="Fri, 10 Sep 2026 00:00:00 GMT", rule-id="..."`.
+fn parse_expiry_date(expiration: Option<String>) -> Option<time::PrimitiveDateTime> {
+ expiration
+ .as_deref()
+ .and_then(|value| value.split("expiry-date=\"").nth(1))
+ .and_then(|rest| rest.split('"').next())
+ .and_then(parse_http_date)
+}
+
+/// An HTTP-date spells the zone `GMT` rather than `+0000`, which RFC 2822 only accepts under its
+/// obsolete-zone rules, so fall back to reading the shape directly.
+fn parse_http_date(date: &str) -> Option<time::PrimitiveDateTime> {
+ let from_rfc_2822 =
+ time::OffsetDateTime::parse(date, &time::format_description::well_known::Rfc2822)
+ .ok()
+ .map(|value| time::PrimitiveDateTime::new(value.date(), value.time()));
+
+ from_rfc_2822.or_else(|| {
+ time::format_description::parse(
+ "[weekday repr:short], [day] [month repr:short] [year] [hour]:[minute]:[second] GMT",
+ )
+ .ok()
+ .and_then(|description| time::PrimitiveDateTime::parse(date, &description).ok())
+ })
+}
+
+#[async_trait::async_trait]
+impl ProcessTrackerWorkflow<SessionState> for BlocklistExportWorkflow {
+ #[instrument(skip_all, fields(flow = ?router_env::Flow::CreateBlocklistExport))]
+ async fn execute_workflow<'a>(
+ &'a self,
+ state: &'a SessionState,
+ process: storage::ProcessTracker,
+ ) -> Result<(), errors::ProcessTrackerError> {
+ let db = &*state.store;
+
+ let tracking_data: storage::BlocklistExportTrackingData = process
+ .tracking_data
+ .clone()
+ .parse_value("BlocklistExportTrackingData")
+ .map_err(errors::ProcessTrackerError::from)?;
+
+ let job_id = tracking_data.job_id.clone();
+ let profile_id = tracking_data.profile_id.clone();
+ let merchant_id = tracking_data
+ .processor_merchant_id
+ .clone()
+ .unwrap_or_else(|| tracking_data.merchant_id.clone());
+ let merchant_id_str = merchant_id.get_string_repr();
+
+ 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,
+ total_rows: None,
+ file_key: None,
+ error_message: None,
+ expires_at: None,
+ updated_at: common_utils::date_time::now(),
+ },
+ )
+ .await
+ .map_err(errors::ProcessTrackerError::from)?;
+
+ let result = run_export_job(state, &process.id, tracking_data, &merchant_id).await;
+
+ match result {
+ Ok((row_count, expiration)) => {
+ let total_rows = i32::try_from(row_count)
+ .map_err(|_| errors::ProcessTrackerError::UnexpectedFlow)?;
+
+ 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(total_rows),
+ failed_rows: None,
+ total_rows: Some(total_rows),
+ file_key: Some(export::export_key(
+ merchant_id_str,
+ profile_id.get_string_repr(),
+ &job_id,
+ )),
+ error_message: None,
+ expires_at: parse_expiry_date(expiration),
+ updated_at: common_utils::date_time::now(),
+ },
+ )
+ .await
+ .map_err(errors::ProcessTrackerError::from)?;
+
+ info!(
+ job_id = %job_id,
+ row_count,
+ "Blocklist export completed"
+ );
+
+ 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,
+ "Blocklist export 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,
+ "Blocklist export exceeded max retries, marking failed"
+ );
+ 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: None,
+ total_rows: None,
+ file_key: None,
+ error_message: Some(
+ "Export failed after repeated attempts. Please retry."
+ .to_string(),
+ ),
+ expires_at: None,
+ 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(())
+ }
+
+ 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 86553e1f79..307e73dc0b 100644
--- a/crates/router_env/src/logger/types.rs
+++ b/crates/router_env/src/logger/types.rs
@@ -351,6 +351,8 @@ pub enum Flow {
GetBlocklistCount,
/// Look up whether a value is present in the blocklist
LookupBlocklistEntry,
+ /// Start a CSV export of the blocklist
+ CreateBlocklistExport,
/// Incoming Webhook Receive
IncomingWebhookReceive,
/// Recovery incoming webhook receive
diff --git a/migrations/2026-09-04-100000_add_export_columns_to_batch_blocklist_jobs/down.sql b/migrations/2026-09-04-100000_add_export_columns_to_batch_blocklist_jobs/down.sql
new file mode 100644
index 0000000000..2ce195d930
--- /dev/null
+++ b/migrations/2026-09-04-100000_add_export_columns_to_batch_blocklist_jobs/down.sql
@@ -0,0 +1,6 @@
+ALTER TABLE batch_blocklist_jobs
+ DROP COLUMN IF EXISTS expires_at,
+ DROP COLUMN IF EXISTS error_message,
+ DROP COLUMN IF EXISTS file_key,
+ DROP COLUMN IF EXISTS file_name,
+ DROP COLUMN IF EXISTS job_type;
diff --git a/migrations/2026-09-04-100000_add_export_columns_to_batch_blocklist_jobs/up.sql b/migrations/2026-09-04-100000_add_export_columns_to_batch_blocklist_jobs/up.sql
new file mode 100644
index 0000000000..e9bf9d3970
--- /dev/null
+++ b/migrations/2026-09-04-100000_add_export_columns_to_batch_blocklist_jobs/up.sql
@@ -0,0 +1,9 @@
+ALTER TABLE batch_blocklist_jobs
+ ADD COLUMN IF NOT EXISTS job_type VARCHAR(32),
+ ADD COLUMN IF NOT EXISTS file_name VARCHAR(255),
+ ADD COLUMN IF NOT EXISTS file_key VARCHAR(512),
+ ADD COLUMN IF NOT EXISTS error_message TEXT,
+ ADD COLUMN IF NOT EXISTS expires_at TIMESTAMP;
+
+-- Every row that predates exports is an upload, so the listing can filter on the value alone.
+UPDATE batch_blocklist_jobs SET job_type = 'upload' WHERE job_type IS NULL;