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

22.8 KB
Raw Blame
//! Analytics reports generated by the process tracker instead of the reporting Lambdas.
//!
//! [`generate_report`] invokes the report's Lambda, or enqueues an `AnalyticsReportWorkflow` task,
//! as `report_download_config` selects for that report. The task writes the CSV to file storage,
//! then sends a download link by webhook to the request's `return_url`, or by email. The webhook
//! keeps the Lambda's fields and its `X-Webhook-Signature-512` header.

use analytics::{
    enums::AuthInfo,
    errors::AnalyticsError,
    lambda_utils::invoke_lambda,
    reports::{self, ReportKind},
};
use api_models::analytics::GenerateReportRequest;
use common_utils::{
    crypto::{HmacSha512, SignMessage},
    date_time,
    errors::CustomResult,
    pii::Email,
    request::RequestContent,
};
use error_stack::{report, ResultExt};
use external_services::file_storage::MultipartUpload;
use hyperswitch_masking::PeekInterface;
use router_env::instrument;

use crate::{
    logger,
    routes::SessionState,
    services::{self, ApplicationResponse},
    types::storage,
};

const ANALYTICS_REPORT_TASK: &str = "ANALYTICS_REPORT";

/// The Lambda gave the merchant's endpoint 10 seconds.
const WEBHOOK_TIMEOUT_SECS: u64 = 10;

#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct AnalyticsReportTrackingData {
    pub job_id: String,
    pub report: ReportKind,
    /// As the handler built it, with `time_range.end_time` always set. Its
    /// `payment_response_hash_key` is never stored: the signing key is read again on delivery.
    pub request: GenerateReportRequest,
    pub file_key: String,
    /// Set once the file is written; from then on retries only redo delivery.
    #[serde(default)]
    pub generated: bool,
}

impl AnalyticsReportTrackingData {
    fn time_range(&self) -> (time::PrimitiveDateTime, time::PrimitiveDateTime) {
        let range = self.request.request.time_range;
        (range.start_time, range.end_time.unwrap_or(range.start_time))
    }

    /// Also the download's name. The range carries no separators, so the name is valid on every
    /// file system.
    fn file_name(&self) -> String {
        let (start, end) = self.time_range();
        let compact = |value| {
            date_time::format_date(value, date_time::DateFormat::YYYYMMDDHHmmss)
                .unwrap_or_else(|_| value.to_string())
        };
        let name = self.report.definition().name;
        format!("{name}_report_{}_{}.csv", compact(start), compact(end))
    }

    /// The org, merchant and profile naming the report in its file key and webhook. A connected
    /// merchant is named by its platform, as the Lambda did.
    fn owner(&self) -> (&str, Option<&str>, Option<&str>) {
        match &self.request.auth {
            AuthInfo::OrgLevel { org_id } => (org_id.get_string_repr(), None, None),
            AuthInfo::MerchantLevel {
                org_id,
                merchant_ids,
                ..
            } => (
                org_id.get_string_repr(),
                merchant_ids.first().map(|id| id.get_string_repr()),
                None,
            ),
            AuthInfo::ProfileLevel {
                org_id,
                merchant_id,
                profile_ids,
                ..
            } => (
                org_id.get_string_repr(),
                Some(merchant_id.get_string_repr()),
                profile_ids.first().map(|id| id.get_string_repr()),
            ),
        }
    }

    /// The Lambda's key layout, with the job id added so two requests for the same range cannot
    /// overwrite each other's file.
    fn file_key(&self, prefix: &str) -> String {
        let (org_id, merchant_id, profile_id) = self.owner();
        let owner = [Some(org_id), merchant_id, profile_id]
            .into_iter()
            .flatten()
            .collect::<Vec<_>>()
            .join("/");
        let name = self.report.definition().name;
        format!(
            "{prefix}/{owner}/{name}/{}/{}",
            self.job_id,
            self.file_name()
        )
    }
}

/// Starts `report` on the process tracker when `report_download_config.process_tracker_reports`
/// lists it, else on its Lambda.
pub async fn generate_report(
    state: &SessionState,
    report: ReportKind,
    request: GenerateReportRequest,
) -> CustomResult<ApplicationResponse<()>, AnalyticsError> {
    let config = &state.conf.report_download_config;
    let report = report.requested_by(&request.request);
    match config.uses_process_tracker(report) {
        false => {
            let json_bytes =
                serde_json::to_vec(&request).map_err(|_| AnalyticsError::UnknownError)?;
            invoke_lambda(config.lambda_function(report), &config.region, &json_bytes)
                .await
                .map(ApplicationResponse::Json)
        }
        true => enqueue_report(state, report, request)
            .await
            .map(ApplicationResponse::Json),
    }
}

#[instrument(skip_all, fields(report = ?report))]
async fn enqueue_report(
    state: &SessionState,
    report: ReportKind,
    mut request: GenerateReportRequest,
) -> CustomResult<(), AnalyticsError> {
    // Rejected here, with a 400, rather than failing in the background.
    report.validate_columns(&request)?;

    let now = date_time::now();
    request.payment_response_hash_key = None;
    request.request.time_range.end_time.get_or_insert(now);

    let job_id = common_utils::generate_id(crate::consts::ID_LENGTH, "report");
    let mut tracking_data = AnalyticsReportTrackingData {
        job_id: job_id.clone(),
        report,
        request,
        file_key: String::new(),
        generated: false,
    };
    tracking_data.file_key = tracking_data.file_key(
        &state
            .conf
            .report_download_config
            .process_tracker
            .file_key_prefix,
    );

    let runner = storage::ProcessTrackerRunner::AnalyticsReportWorkflow;
    let entry = storage::ProcessTrackerNew::new(
        format!("{runner}_{ANALYTICS_REPORT_TASK}_{job_id}"),
        ANALYTICS_REPORT_TASK,
        runner,
        ["ANALYTICS", "REPORT"],
        tracking_data,
        None,
        now,
        common_types::consts::API_VERSION,
        common_enums::ApplicationSource::Main,
    )
    .change_context(AnalyticsError::UnknownError)?;

    state
        .store
        .insert_process(entry)
        .await
        .change_context(AnalyticsError::UnknownError)
        .attach_printable("Failed to enqueue the analytics report")?;

    logger::info!(job_id = %job_id, "Analytics report enqueued");
    Ok(())
}

/// Writes the report's CSV to `file_key`, returning the number of rows in it. The replica's rows
/// arrive a page at a time and each page is uploaded before the next is taken, so memory never
/// holds more than a few pages.
pub(crate) async fn generate_report_file(
    state: &SessionState,
    tracking_data: &AnalyticsReportTrackingData,
) -> CustomResult<usize, AnalyticsError> {
    let settings = &state.conf.report_download_config.process_tracker;
    let query = tracking_data.report.query(&tracking_data.request)?;
    let header = query.header.clone();
    let mut upload =
        MultipartUpload::start(state.file_storage_client.as_ref(), &tracking_data.file_key)
            .await
            .change_context(AnalyticsError::UnknownError)?;

    // One page queued while another is written: the reader waits rather than running ahead.
    let (sender, receiver) = tokio::sync::mpsc::channel(1);
    let read = state.store.stream_analytics_report(
        query,
        settings.page_size,
        std::time::Duration::from_secs(settings.query_timeout_secs),
        sender,
    );
    let write = async {
        // Dropped on the way out, which stops the reader if writing fails first.
        let mut pages = receiver;
        upload
            .write(&header)
            .await
            .change_context(AnalyticsError::UnknownError)?;
        let mut row_count = 0;
        while let Some(page) = pages.recv().await {
            let mut records = Vec::new();
            for row in &page {
                records.extend(reports::csv_record(
                    row.cells
                        .iter()
                        .map(|cell| cell.as_deref().unwrap_or_default()),
                ));
            }
            upload
                .write(&records)
                .await
                .change_context(AnalyticsError::UnknownError)?;
            row_count += page.len();
        }
        Ok::<_, error_stack::Report<AnalyticsError>>(row_count)
    };
    let (read, written) = tokio::join!(read, write);

    let written = read
        .change_context(AnalyticsError::UnknownError)
        .attach_printable("Failed to read the report from the replica")
        .and(written);
    match written {
        Ok(row_count) => {
            upload
                .finish()
                .await
                .change_context(AnalyticsError::UnknownError)?;
            Ok(row_count)
        }
        Err(error) => {
            if let Err(abort_error) = upload.abort().await {
                logger::warn!(?abort_error, "Failed to abort the analytics report upload");
            }
            Err(error)
        }
    }
}

/// Sends the download link by webhook when the request names a `return_url`, else by email.
pub(crate) async fn deliver_report(
    state: &SessionState,
    tracking_data: &AnalyticsReportTrackingData,
) -> CustomResult<(), AnalyticsError> {
    let expiry_days = state
        .conf
        .report_download_config
        .process_tracker
        .download_url_expiry_days;
    let download_url = state
        .file_storage_client
        .get_presigned_download_url(
            &tracking_data.file_key,
            std::time::Duration::from_secs(u64::from(expiry_days) * 86_400),
            Some(&tracking_data.file_name()),
        )
        .await
        .change_context(AnalyticsError::UnknownError)
        .attach_printable("Failed to sign the analytics report download URL")?;

    if tracking_data.request.request.return_url.is_none() {
        return send_emails(state, tracking_data, download_url.as_str(), expiry_days).await;
    }
    let (start, end) = tracking_data.time_range();
    let data = serde_json::json!({
        "report_type": tracking_data.report.definition().webhook_type,
        "start_date_utc": reports::format_timestamp(start),
        "end_date_utc": reports::format_timestamp(end),
        "download_url": download_url.as_str(),
        "expires_in_hours": expiry_days * 24,
    });
    send_webhook(state, tracking_data, "report_generation.completed", data).await
}

/// Tells the merchant's endpoint the report could not be produced, once retries are exhausted.
pub(crate) async fn notify_report_failed(
    state: &SessionState,
    tracking_data: &AnalyticsReportTrackingData,
) -> CustomResult<(), AnalyticsError> {
    let data = serde_json::json!({
        "code": "internal_server_error",
        "message": "We could not generate the report due to a internal server error. Please request the report again.",
    });
    send_webhook(state, tracking_data, "report_generation.failed", data).await
}

fn webhook_body(
    tracking_data: &AnalyticsReportTrackingData,
    event: &str,
    data: serde_json::Value,
) -> Vec<u8> {
    // The Lambda's key order: org, merchant, profile when there is one, data, event.
    let (org_id, merchant_id, profile_id) = tracking_data.owner();
    let mut payload = serde_json::Map::new();
    payload.insert("org_id".into(), org_id.into());
    payload.insert("merchant_id".into(), merchant_id.into());
    if let Some(profile_id) = profile_id {
        payload.insert("profile_id".into(), profile_id.into());
    }
    payload.insert("data".into(), data);
    payload.insert("event".into(), event.into());
    serde_json::Value::Object(payload).to_string().into_bytes()
}

/// Posts `event` to the request's `return_url`; does nothing when it has none.
async fn send_webhook(
    state: &SessionState,
    tracking_data: &AnalyticsReportTrackingData,
    event: &str,
    data: serde_json::Value,
) -> CustomResult<(), AnalyticsError> {
    let Some(url) = tracking_data.request.request.return_url.as_ref() else {
        return Ok(());
    };
    let body = webhook_body(tracking_data, event, data);
    let mut request = services::RequestBuilder::new()
        .method(services::Method::Post)
        .url(url.get_string_repr())
        .header("Content-Type", "application/json")
        .header("User-Agent", "Hyperswitch-Webhook/1.0");
    if let Some(hash_key) = payment_response_hash_key(state, &tracking_data.request).await? {
        request = request.header(
            "X-Webhook-Signature-512",
            &webhook_signature(&hash_key, &body)?,
        );
    }

    let response = state
        .api_client
        .send_request(
            state,
            request.set_body(RequestContent::RawBytes(body)).build(),
            Some(WEBHOOK_TIMEOUT_SECS),
            false,
        )
        .await
        .change_context(AnalyticsError::UnknownError)
        .attach_printable("Failed to reach the analytics report webhook endpoint")?;

    let status = response.status();
    if !status.is_success() {
        return Err(report!(AnalyticsError::UnknownError)).attach_printable(format!(
            "The report webhook endpoint responded with {status}"
        ));
    }
    Ok(())
}

/// Lowercase hex HMAC-SHA512 of the body, as the Lambda signed it.
fn webhook_signature(hash_key: &str, body: &[u8]) -> CustomResult<String, AnalyticsError> {
    HmacSha512
        .sign_message(hash_key.as_bytes(), body)
        .map(hex::encode)
        .change_context(AnalyticsError::UnknownError)
}

/// `request.merchant_id` holds the key store's merchant; organization reports have none and go
/// unsigned, as they did from the Lambda.
async fn payment_response_hash_key(
    state: &SessionState,
    request: &GenerateReportRequest,
) -> CustomResult<Option<String>, AnalyticsError> {
    let Some(merchant_id) = request.merchant_id.as_ref() else {
        return Ok(None);
    };
    let key_store_master_key = state.store.get_master_key().to_vec().into();
    let key_store = state
        .accounts_store
        .get_merchant_key_store_by_merchant_id(merchant_id, &key_store_master_key)
        .await
        .change_context(AnalyticsError::UnknownError)?;
    crate::utils::get_payment_response_hash_key(state, &key_store, &request.auth).await
}

async fn send_emails(
    state: &SessionState,
    tracking_data: &AnalyticsReportTrackingData,
    download_url: &str,
    expiry_days: u32,
) -> CustomResult<(), AnalyticsError> {
    #[cfg(feature = "email")]
    {
        let config = &state.conf.report_download_config.process_tracker;
        let (start, end) = tracking_data.time_range();
        let report = tracking_data.report;
        let definition = report.definition();
        let email = services::email::types::AnalyticsReportEmail {
            recipients: email_recipients(&tracking_data.request, config.email_bcc(report)),
            report_name: format!("{} {}", config.email_env_label, definition.title),
            noun: definition.noun.to_owned(),
            covers: definition.covers.to_owned(),
            start: reports::format_timestamp(start),
            end: reports::format_timestamp(end),
            download_url: download_url.to_owned(),
            expiry: match expiry_days {
                1 => "1 day".to_owned(),
                days => format!("{days} days"),
            },
        };
        state
            .email_client
            .compose_and_send_email(
                crate::utils::user::get_base_url(state),
                Box::new(email),
                state.conf.proxy.https_url.as_ref(),
            )
            .await
            .change_context(AnalyticsError::UnknownError)
            .attach_printable("Failed to send the analytics report email")
    }

    #[cfg(not(feature = "email"))]
    {
        let _ = (state, tracking_data, download_url, expiry_days);
        Err(report!(AnalyticsError::NotImplemented(
            "Emailing analytics reports without the email feature"
        )))
    }
}

/// One email to the requester and the other requested addresses, blind-copying the BCC list;
/// each address once, ignoring case.
#[cfg(any(feature = "email", test))]
fn email_recipients(
    request: &GenerateReportRequest,
    bcc: &[Email],
) -> external_services::email::EmailRecipients {
    let mut recipients = external_services::email::EmailRecipients::default();
    let seen = |list: &[Email], email: &Email| {
        list.iter()
            .any(|existing| existing.peek().eq_ignore_ascii_case(email.peek()))
    };
    for email in std::iter::once(&request.email).chain(request.request.emails.iter().flatten()) {
        if !seen(&recipients.to, email) {
            recipients.to.push(email.clone());
        }
    }
    for email in bcc {
        if !seen(&recipients.to, email) && !seen(&recipients.bcc, email) {
            recipients.bcc.push(email.clone());
        }
    }
    recipients
}

/// Saves `tracking_data` on the task. The business status stays `Pending` until the task finishes,
/// since the consumer skips any task whose business status is anything else.
pub(crate) async fn persist_tracking_data(
    state: &SessionState,
    process_id: &str,
    tracking_data: &AnalyticsReportTrackingData,
) -> CustomResult<(), AnalyticsError> {
    let value = serde_json::to_value(tracking_data).change_context(AnalyticsError::UnknownError)?;
    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(date_time::now()),
            },
        )
        .await
        .change_context(AnalyticsError::UnknownError)
        .attach_printable("Failed to save analytics report progress")?;
    Ok(())
}

#[cfg(test)]
#[allow(clippy::unwrap_used)]
mod tests {
    use api_models::analytics::ReportRequest;
    use common_utils::id_type;

    use super::*;

    fn tracking_data(auth: AuthInfo, emails: Option<Vec<Email>>) -> AnalyticsReportTrackingData {
        AnalyticsReportTrackingData {
            job_id: "report_abc".to_owned(),
            report: ReportKind::V1Payments,
            request: GenerateReportRequest {
                request: ReportRequest {
                    time_range: common_utils::types::TimeRange {
                        start_time: time::macros::datetime!(2026-10-01 00:00:00),
                        end_time: Some(time::macros::datetime!(2026-10-07 23:59:59.999)),
                    },
                    emails,
                    return_url: None,
                    #[cfg(feature = "v2")]
                    report_type: Default::default(),
                    columns: None,
                },
                merchant_id: None,
                auth,
                email: Email::try_from("[email protected]".to_owned()).unwrap(),
                payment_response_hash_key: None,
            },
            file_key: String::new(),
            generated: false,
        }
    }

    fn profile_auth() -> AuthInfo {
        AuthInfo::ProfileLevel {
            org_id: id_type::OrganizationId::try_from(std::borrow::Cow::from("org_1")).unwrap(),
            merchant_id: id_type::MerchantId::try_from(std::borrow::Cow::from("merchant_1"))
                .unwrap(),
            profile_ids: vec![
                id_type::ProfileId::try_from(std::borrow::Cow::from("pro_1")).unwrap(),
            ],
            processor_merchant_id: None,
        }
    }

    #[test]
    fn file_key_follows_lambda_layout() {
        assert_eq!(
            tracking_data(profile_auth(), None).file_key("analytics_reports"),
            "analytics_reports/org_1/merchant_1/pro_1/v1_payments/report_abc/\
             v1_payments_report_20261001000000_20261007235959.csv"
        );
    }

    #[test]
    fn webhook_body_carries_lambda_fields() {
        let data = tracking_data(profile_auth(), None);
        let body = webhook_body(
            &data,
            "report_generation.completed",
            serde_json::json!({
                "report_type": "payment_report",
                "start_date_utc": "2026-10-01T00:00:00.000Z",
                "end_date_utc": "2026-10-07T23:59:59.999Z",
                "download_url": "https://bucket.example/key?X-Amz-Signature=ab",
                "expires_in_hours": 168,
            }),
        );

        // Field order follows build_webhook_payload in weekly_payment_report_generator_step_2.
        assert_eq!(
            String::from_utf8(body.clone()).unwrap(),
            r#"{"org_id":"org_1","merchant_id":"merchant_1","profile_id":"pro_1","data":{"report_type":"payment_report","start_date_utc":"2026-10-01T00:00:00.000Z","end_date_utc":"2026-10-07T23:59:59.999Z","download_url":"https://bucket.example/key?X-Amz-Signature=ab","expires_in_hours":168},"event":"report_generation.completed"}"#
        );
        // Python: hmac.new(b"whsec_test_key", body, hashlib.sha512).hexdigest()
        assert_eq!(
            webhook_signature("whsec_test_key", &body).unwrap(),
            "76f475de13962c74f934f8dc2e21a88b2ae3d5f3ba825e523a15089c90dd5251ae895f87aa4d1c8bffc60004fdfbc546cd9666c4946640876d44a20fc8577ed1"
        );
    }

    #[test]
    fn organization_webhook_has_no_merchant_or_profile() {
        let auth = AuthInfo::OrgLevel {
            org_id: id_type::OrganizationId::try_from(std::borrow::Cow::from("org_1")).unwrap(),
        };
        let body = webhook_body(
            &tracking_data(auth, None),
            "report_generation.failed",
            serde_json::json!({
                "code": "internal_server_error",
                "message": "We could not generate the report due to a internal server error. Please request the report again.",
            }),
        );
        assert_eq!(
            String::from_utf8(body).unwrap(),
            r#"{"org_id":"org_1","merchant_id":null,"data":{"code":"internal_server_error","message":"We could not generate the report due to a internal server error. Please request the report again."},"event":"report_generation.failed"}"#
        );
    }

    #[test]
    fn email_recipients_are_deduplicated() {
        let email = |value: &str| Email::try_from(value.to_owned()).unwrap();
        let data = tracking_data(
            profile_auth(),
            Some(vec![email("[email protected]"), email("[email protected]")]),
        );
        let recipients = email_recipients(
            &data.request,
            &[email("[email protected]"), email("[email protected]")],
        );
        let addresses =
            |list: &[Email]| list.iter().map(|e| e.peek().to_owned()).collect::<Vec<_>>();
        assert_eq!(
            addresses(&recipients.to),
            ["[email protected]", "[email protected]"]
        );
        assert_eq!(addresses(&recipients.bcc), ["[email protected]"]);
    }
}