use thiserror::Error;
use crate::i18n::{I18nBundle, Locale};
#[derive(Error, Debug)]
pub enum DomainError {
#[error("Crawler configuration error: {message}")]
CrawlConfigError {
message: String,
#[source]
source: Option<Box<dyn std::error::Error + Send + Sync>>,
},
#[error("Crawl depth exceeded: maximum {max}, requested {requested}")]
CrawlDepthExceeded { max: u32, requested: u32 },
#[error("URL path excluded by filter rules: {path}")]
PathFiltered { path: String },
#[error("Task not found: {task_id}")]
TaskNotFound { task_id: crate::domain::id::Id },
#[error("Invalid task state: current {current}, expected {expected}")]
InvalidTaskState { current: String, expected: String },
#[error("Task expired: created at {created_at}, timeout {timeout_seconds}s")]
TaskExpired {
created_at: chrono::DateTime<chrono::Utc>,
timeout_seconds: u64,
},
#[error("Team not found: {team_id}")]
TeamNotFound { team_id: crate::domain::id::Id },
#[error("Insufficient credits: required {required}, available {available}")]
InsufficientCredits { required: i64, available: i64 },
#[error("Team concurrency limit: current {current}, limit {limit}")]
ConcurrencyLimitExceeded { current: usize, limit: usize },
#[error("Invalid URL: {url}")]
InvalidUrl { url: String },
#[error("URL is blacklisted: {domain}")]
DomainBlacklisted { domain: String },
#[error("URL is forbidden by robots.txt: {url}")]
RobotsForbidden { url: String },
#[error("Webhook delivery failed: {url}, status {status}")]
WebhookDeliveryFailed { url: String, status: u16 },
#[error("Invalid webhook URL: {url}")]
InvalidWebhookUrl { url: String },
#[error("LLM extraction failed: model {model}, error: {message}")]
LLMExtractionFailed { model: String, message: String },
#[error("Invalid CSS selector: {selector}")]
InvalidCssSelector { selector: String },
#[error("Validation failed: {field} - {message}")]
ValidationError { field: String, message: String },
}
impl DomainError {
pub fn crawl_config(message: impl Into<String>) -> Self {
DomainError::CrawlConfigError {
message: message.into(),
source: None,
}
}
pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
DomainError::ValidationError {
field: field.into(),
message: message.into(),
}
}
pub fn user_message_locale(&self, locale: &Locale, bundle: &I18nBundle) -> String {
match self {
DomainError::CrawlConfigError { message, .. } => bundle.translate_with_args(
locale,
"domain-error-crawl-config",
&[("message", message.as_str().to_string())],
),
DomainError::CrawlDepthExceeded { max, requested } => bundle.translate_with_args(
locale,
"domain-error-depth-exceeded",
&[
("max", (*max as i64).to_string()),
("requested", (*requested as i64).to_string()),
],
),
DomainError::PathFiltered { path } => bundle.translate_with_args(
locale,
"domain-error-path-filtered",
&[("path", path.as_str().to_string())],
),
DomainError::TaskNotFound { task_id } => bundle.translate_with_args(
locale,
"domain-error-task-not-found",
&[("task_id", task_id.to_string())],
),
DomainError::InvalidTaskState { current, expected } => bundle.translate_with_args(
locale,
"domain-error-invalid-task-state",
&[
("current", current.as_str().to_string()),
("expected", expected.as_str().to_string()),
],
),
DomainError::TaskExpired { .. } => {
bundle.translate(locale, "domain-error-task-expired")
}
DomainError::TeamNotFound { team_id } => bundle.translate_with_args(
locale,
"domain-error-team-not-found",
&[("team_id", team_id.to_string())],
),
DomainError::InsufficientCredits {
required,
available,
} => bundle.translate_with_args(
locale,
"domain-error-insufficient-credits",
&[
("required", (*required).to_string()),
("available", (*available).to_string()),
],
),
DomainError::ConcurrencyLimitExceeded { current, limit } => bundle.translate_with_args(
locale,
"domain-error-concurrency-limit",
&[
("current", (*current as i64).to_string()),
("limit", (*limit as i64).to_string()),
],
),
DomainError::InvalidUrl { url } => bundle.translate_with_args(
locale,
"domain-error-invalid-url",
&[("url", url.as_str().to_string())],
),
DomainError::DomainBlacklisted { domain } => bundle.translate_with_args(
locale,
"domain-error-domain-blacklisted",
&[("domain", domain.as_str().to_string())],
),
DomainError::RobotsForbidden { url } => bundle.translate_with_args(
locale,
"domain-error-robots-forbidden",
&[("url", url.as_str().to_string())],
),
DomainError::WebhookDeliveryFailed { .. } => {
bundle.translate(locale, "domain-error-webhook-delivery-failed")
}
DomainError::InvalidWebhookUrl { url } => bundle.translate_with_args(
locale,
"domain-error-invalid-webhook-url",
&[("url", url.as_str().to_string())],
),
DomainError::LLMExtractionFailed { .. } => {
bundle.translate(locale, "domain-error-llm-extraction-failed")
}
DomainError::InvalidCssSelector { selector } => bundle.translate_with_args(
locale,
"domain-error-invalid-css-selector",
&[("selector", selector.as_str().to_string())],
),
DomainError::ValidationError { field, message } => bundle.translate_with_args(
locale,
"domain-error-validation",
&[
("field", field.as_str().to_string()),
("message", message.as_str().to_string()),
],
),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::error::Error as _;
#[test]
fn test_insufficient_credits_error() {
let error = DomainError::InsufficientCredits {
required: 100,
available: 50,
};
let msg = error.to_string();
assert!(msg.contains("Insufficient credits"));
assert!(msg.contains("100"));
assert!(msg.contains("50"));
}
#[test]
fn test_validation_error() {
let error = DomainError::validation("url", "Invalid format");
let msg = error.to_string();
assert!(msg.contains("Validation failed"));
assert!(msg.contains("url"));
assert!(msg.contains("Invalid format"));
}
#[test]
fn test_task_not_found() {
let task_id = crate::domain::id::Id::generate();
let error = DomainError::TaskNotFound { task_id };
let msg = error.to_string();
assert!(msg.contains("Task not found"));
assert!(msg.contains(&task_id.to_string()));
}
#[test]
fn test_invalid_url() {
let error = DomainError::InvalidUrl {
url: "not-a-url".to_string(),
};
let msg = error.to_string();
assert!(msg.contains("Invalid URL"));
assert!(msg.contains("not-a-url"));
}
#[test]
fn test_crawl_config_error_without_source() {
let error = DomainError::crawl_config("missing field");
let msg = error.to_string();
assert!(msg.contains("Crawler configuration error"));
assert!(msg.contains("missing field"));
assert!(error.source().is_none());
}
#[test]
fn test_crawl_config_error_with_source() {
let source_err = std::io::Error::other("io failed");
let error = DomainError::CrawlConfigError {
message: "wrapped".to_string(),
source: Some(Box::new(source_err)),
};
let msg = error.to_string();
assert!(msg.contains("Crawler configuration error"));
assert!(msg.contains("wrapped"));
let src = error.source();
assert!(src.is_some());
assert!(src.unwrap().to_string().contains("io failed"));
}
#[test]
fn test_crawl_depth_exceeded() {
let error = DomainError::CrawlDepthExceeded {
max: 5,
requested: 10,
};
let msg = error.to_string();
assert!(msg.contains("Crawl depth exceeded"));
assert!(msg.contains("5"));
assert!(msg.contains("10"));
}
#[test]
fn test_crawl_depth_exceeded_boundary_zero() {
let error = DomainError::CrawlDepthExceeded {
max: 0,
requested: 1,
};
let msg = error.to_string();
assert!(msg.contains("maximum 0"));
assert!(msg.contains("requested 1"));
}
#[test]
fn test_path_filtered() {
let error = DomainError::PathFiltered {
path: "/admin/*".to_string(),
};
let msg = error.to_string();
assert!(msg.contains("URL path excluded by filter rules"));
assert!(msg.contains("/admin/*"));
}
#[test]
fn test_path_filtered_empty_string() {
let error = DomainError::PathFiltered {
path: String::new(),
};
let msg = error.to_string();
assert!(msg.contains("URL path excluded by filter rules"));
assert!(!msg.is_empty());
}
#[test]
fn test_invalid_task_state() {
let error = DomainError::InvalidTaskState {
current: "Running".to_string(),
expected: "Pending".to_string(),
};
let msg = error.to_string();
assert!(msg.contains("Invalid task state"));
assert!(msg.contains("Running"));
assert!(msg.contains("Pending"));
}
#[test]
fn test_task_expired() {
let created_at = chrono::Utc::now();
let error = DomainError::TaskExpired {
created_at,
timeout_seconds: 60,
};
let msg = error.to_string();
assert!(msg.contains("Task expired"));
assert!(msg.contains(&created_at.format("%Y").to_string()));
assert!(msg.contains("60"));
}
#[test]
fn test_task_expired_boundary_zero_timeout() {
let created_at = chrono::Utc::now();
let error = DomainError::TaskExpired {
created_at,
timeout_seconds: 0,
};
let msg = error.to_string();
assert!(msg.contains("timeout 0s"));
}
#[test]
fn test_team_not_found() {
let team_id = crate::domain::id::Id::generate();
let error = DomainError::TeamNotFound { team_id };
let msg = error.to_string();
assert!(msg.contains("Team not found"));
assert!(msg.contains(&team_id.to_string()));
}
#[test]
fn test_team_not_found_nil_uuid() {
let team_id = crate::domain::id::Id::nil();
let error = DomainError::TeamNotFound { team_id };
let msg = error.to_string();
assert!(msg.contains("Team not found"));
assert!(msg.contains("00000000-0000-0000-0000-000000000000"));
}
#[test]
fn test_concurrency_limit_exceeded() {
let error = DomainError::ConcurrencyLimitExceeded {
current: 11,
limit: 10,
};
let msg = error.to_string();
assert!(msg.contains("Team concurrency limit"));
assert!(msg.contains("11"));
assert!(msg.contains("10"));
}
#[test]
fn test_concurrency_limit_exceeded_boundary_zero() {
let error = DomainError::ConcurrencyLimitExceeded {
current: 0,
limit: 0,
};
let msg = error.to_string();
assert!(msg.contains("current 0"));
assert!(msg.contains("limit 0"));
}
#[test]
fn test_domain_blacklisted() {
let error = DomainError::DomainBlacklisted {
domain: "example.com".to_string(),
};
let msg = error.to_string();
assert!(msg.contains("URL is blacklisted"));
assert!(msg.contains("example.com"));
}
#[test]
fn test_robots_forbidden() {
let error = DomainError::RobotsForbidden {
url: "https://example.com/private".to_string(),
};
let msg = error.to_string();
assert!(msg.contains("URL is forbidden by robots.txt"));
assert!(msg.contains("https://example.com/private"));
}
#[test]
fn test_webhook_delivery_failed() {
let error = DomainError::WebhookDeliveryFailed {
url: "https://hook.example.com".to_string(),
status: 503,
};
let msg = error.to_string();
assert!(msg.contains("Webhook delivery failed"));
assert!(msg.contains("https://hook.example.com"));
assert!(msg.contains("503"));
}
#[test]
fn test_webhook_delivery_failed_boundary_status() {
let error = DomainError::WebhookDeliveryFailed {
url: "https://hook.example.com".to_string(),
status: u16::MAX,
};
let msg = error.to_string();
assert!(msg.contains(&u16::MAX.to_string()));
}
#[test]
fn test_invalid_webhook_url() {
let error = DomainError::InvalidWebhookUrl {
url: "ftp://not-webhook".to_string(),
};
let msg = error.to_string();
assert!(msg.contains("Invalid webhook URL"));
assert!(msg.contains("ftp://not-webhook"));
}
#[test]
fn test_llm_extraction_failed() {
let error = DomainError::LLMExtractionFailed {
model: "gpt-4".to_string(),
message: "rate limited".to_string(),
};
let msg = error.to_string();
assert!(msg.contains("LLM extraction failed"));
assert!(msg.contains("gpt-4"));
assert!(msg.contains("rate limited"));
}
#[test]
fn test_invalid_css_selector() {
let error = DomainError::InvalidCssSelector {
selector: "div >".to_string(),
};
let msg = error.to_string();
assert!(msg.contains("Invalid CSS selector"));
assert!(msg.contains("div >"));
}
#[test]
fn test_validation_helper_constructor() {
let error = DomainError::validation("email", "invalid format");
match error {
DomainError::ValidationError { field, message } => {
assert_eq!(field, "email");
assert_eq!(message, "invalid format");
}
_ => panic!("expected ValidationError variant"),
}
}
#[test]
fn test_crawl_config_helper_constructor() {
let error = DomainError::crawl_config("bad config");
match error {
DomainError::CrawlConfigError { message, source } => {
assert_eq!(message, "bad config");
assert!(source.is_none());
}
_ => panic!("expected CrawlConfigError variant"),
}
}
#[test]
fn test_insufficient_credits_boundary_zero() {
let error = DomainError::InsufficientCredits {
required: 0,
available: 0,
};
let msg = error.to_string();
assert!(msg.contains("required 0"));
assert!(msg.contains("available 0"));
}
#[test]
fn test_insufficient_credits_negative_values() {
let error = DomainError::InsufficientCredits {
required: -1,
available: -10,
};
let msg = error.to_string();
assert!(msg.contains("-1"));
assert!(msg.contains("-10"));
}
#[test]
fn test_all_variants_implement_std_error() {
fn assert_error<T: std::error::Error>(_: &T) {}
let errors: Vec<DomainError> = vec![
DomainError::crawl_config("a"),
DomainError::CrawlDepthExceeded {
max: 1,
requested: 2,
},
DomainError::PathFiltered { path: "p".into() },
DomainError::TaskNotFound {
task_id: crate::domain::id::Id::nil(),
},
DomainError::InvalidTaskState {
current: "a".into(),
expected: "b".into(),
},
DomainError::TaskExpired {
created_at: chrono::Utc::now(),
timeout_seconds: 1,
},
DomainError::TeamNotFound {
team_id: crate::domain::id::Id::nil(),
},
DomainError::InsufficientCredits {
required: 1,
available: 0,
},
DomainError::ConcurrencyLimitExceeded {
current: 1,
limit: 0,
},
DomainError::InvalidUrl { url: "u".into() },
DomainError::DomainBlacklisted { domain: "d".into() },
DomainError::RobotsForbidden { url: "u".into() },
DomainError::WebhookDeliveryFailed {
url: "u".into(),
status: 500,
},
DomainError::InvalidWebhookUrl { url: "u".into() },
DomainError::LLMExtractionFailed {
model: "m".into(),
message: "e".into(),
},
DomainError::InvalidCssSelector {
selector: "s".into(),
},
DomainError::ValidationError {
field: "f".into(),
message: "m".into(),
},
];
for err in &errors {
assert_error(err);
}
}
fn make_test_locale() -> Locale {
"en-US".parse().unwrap()
}
fn make_test_bundle() -> I18nBundle {
I18nBundle::load("en-US", &["en-US", "zh-CN"]).unwrap()
}
#[test]
fn test_user_message_locale_crawl_config() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::crawl_config("test error");
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_depth_exceeded() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::CrawlDepthExceeded {
max: 5,
requested: 10,
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_path_filtered() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::PathFiltered {
path: "/secret".into(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_task_not_found() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::TaskNotFound {
task_id: crate::domain::id::Id::nil(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_invalid_task_state() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::InvalidTaskState {
current: "running".into(),
expected: "completed".into(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_task_expired() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::TaskExpired {
created_at: chrono::Utc::now(),
timeout_seconds: 60,
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_team_not_found() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::TeamNotFound {
team_id: crate::domain::id::Id::nil(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_insufficient_credits() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::InsufficientCredits {
required: 100,
available: 50,
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_concurrency_limit() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::ConcurrencyLimitExceeded {
current: 10,
limit: 5,
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_invalid_url() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::InvalidUrl {
url: "not-a-url".into(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_domain_blacklisted() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::DomainBlacklisted {
domain: "evil.com".into(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_robots_forbidden() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::RobotsForbidden {
url: "http://example.com/secret".into(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_webhook_delivery_failed() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::WebhookDeliveryFailed {
url: "http://hook.example.com".into(),
status: 500,
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_invalid_webhook_url() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::InvalidWebhookUrl {
url: "bad-url".into(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_llm_extraction_failed() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::LLMExtractionFailed {
model: "gpt-4".into(),
message: "parse error".into(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_invalid_css_selector() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::InvalidCssSelector {
selector: "[[[bad".into(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_validation() {
let locale = make_test_locale();
let bundle = make_test_bundle();
let err = DomainError::validation("email", "invalid format");
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
#[test]
fn test_user_message_locale_zh_cn() {
let locale: Locale = "zh-CN".parse().unwrap();
let bundle = make_test_bundle();
let err = DomainError::TaskNotFound {
task_id: crate::domain::id::Id::nil(),
};
let msg = err.user_message_locale(&locale, &bundle);
assert!(!msg.is_empty());
}
}