use axum::response::Response;
use log::error;
use crate::common::constants::crawl_task::{CRAWL_TASK_CREDITS_COST, EXTRACT_TASK_CREDITS_COST};
use crate::domain::id::Id;
use crate::domain::models::CreditsTransactionType;
use crate::domain::services::rate_limiting_service::{RateLimitingError, RateLimitingService};
use crate::presentation::handlers::response_builder::errors;
#[derive(Debug, Clone, Copy)]
pub(super) enum CreditCharge<'a> {
Scrape { url: &'a str },
Crawl { url: &'a str },
Extract { url_count: usize },
}
impl CreditCharge<'_> {
fn amount(self) -> i64 {
match self {
Self::Scrape { .. } => 1,
Self::Crawl { .. } => CRAWL_TASK_CREDITS_COST,
Self::Extract { .. } => EXTRACT_TASK_CREDITS_COST,
}
}
fn transaction_type(self) -> CreditsTransactionType {
match self {
Self::Scrape { .. } => CreditsTransactionType::Scrape,
Self::Crawl { .. } => CreditsTransactionType::Crawl,
Self::Extract { .. } => CreditsTransactionType::Extract,
}
}
fn deduct_description(self) -> String {
match self {
Self::Scrape { url } => format!("Scrape URL: {}", url),
Self::Crawl { url } => format!("Crawl URL: {}", url),
Self::Extract { url_count } => format!("Extract {} URL(s)", url_count),
}
}
fn refund_description(self) -> String {
match self {
Self::Scrape { url } => format!("Refund: enqueue failed for {}", url),
Self::Crawl { url } => format!("Refund: crawl creation failed for {}", url),
Self::Extract { url_count } => {
format!("Refund: extract enqueue failed for {} URL(s)", url_count)
}
}
}
fn log_deduct_failure(self, team_id: Id, e: &RateLimitingError) {
if !matches!(self, Self::Crawl { .. }) {
error!("Quota check failed for team {}: {}", team_id, e);
}
}
fn log_refund_failure(self, team_id: Id, amount: i64, e: &RateLimitingError) {
match self {
Self::Scrape { .. } => error!(
"CRITICAL: Failed to refund 1 credit for team {} after enqueue failure: {}",
team_id, e
),
Self::Crawl { .. } => error!(
"CRITICAL: Failed to refund {} credits for team {} after crawl creation failure: {}",
amount, team_id, e
),
Self::Extract { .. } => error!(
"CRITICAL: Failed to refund extract credits for team {}: {}",
team_id, e
),
}
}
}
pub(super) struct CreditFlow<'a> {
service: &'a dyn RateLimitingService,
team_id: Id,
}
impl<'a> CreditFlow<'a> {
pub(super) fn new(service: &'a dyn RateLimitingService, team_id: Id) -> Self {
Self { service, team_id }
}
pub(super) async fn deduct(&self, charge: CreditCharge<'_>) -> Option<Response> {
if let Err(e) = self
.service
.check_and_deduct_quota(
self.team_id,
charge.amount(),
charge.transaction_type(),
charge.deduct_description(),
None,
)
.await
{
charge.log_deduct_failure(self.team_id, &e);
return Some(errors::payment_required(e.to_string()));
}
None
}
pub(super) async fn refund(&self, charge: CreditCharge<'_>, reference_id: Option<Id>) {
if let Err(refund_err) = self
.service
.refund_quota(
self.team_id,
charge.amount(),
charge.refund_description(),
reference_id,
)
.await
{
charge.log_refund_failure(self.team_id, charge.amount(), &refund_err);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scrape_amount_stays_one_credit() {
assert_eq!(CreditCharge::Scrape { url: "u" }.amount(), 1);
assert_eq!(CreditCharge::Crawl { url: "u" }.amount(), 10);
assert_eq!(CreditCharge::Extract { url_count: 3 }.amount(), 8);
}
#[test]
fn descriptions_preserve_existing_wording() {
assert_eq!(
CreditCharge::Scrape { url: "https://a" }.deduct_description(),
"Scrape URL: https://a"
);
assert_eq!(
CreditCharge::Crawl { url: "https://b" }.deduct_description(),
"Crawl URL: https://b"
);
assert_eq!(
CreditCharge::Extract { url_count: 2 }.deduct_description(),
"Extract 2 URL(s)"
);
assert_eq!(
CreditCharge::Scrape { url: "https://a" }.refund_description(),
"Refund: enqueue failed for https://a"
);
assert_eq!(
CreditCharge::Crawl { url: "https://b" }.refund_description(),
"Refund: crawl creation failed for https://b"
);
assert_eq!(
CreditCharge::Extract { url_count: 2 }.refund_description(),
"Refund: extract enqueue failed for 2 URL(s)"
);
}
#[test]
fn transaction_types_match_capability() {
assert_eq!(
CreditCharge::Scrape { url: "u" }.transaction_type(),
CreditsTransactionType::Scrape
);
assert_eq!(
CreditCharge::Crawl { url: "u" }.transaction_type(),
CreditsTransactionType::Crawl
);
assert_eq!(
CreditCharge::Extract { url_count: 1 }.transaction_type(),
CreditsTransactionType::Extract
);
}
}