crawlrs 0.2.0

crawlrs - Enterprise-grade web scraping and crawling platform built with Rust
Documentation
// Copyright (c) 2025-2026 Kirky.X🌠
// SPDX-License-Identifier: Apache-2.0

//! Webhook repository implementation using Sea-ORM with Mapper

use crate::domain::models::Webhook;
use crate::domain::repositories::task_repository::RepositoryError;
use crate::domain::repositories::webhook_repository::WebhookRepository;
use crate::infrastructure::database::entities::webhook;
use crate::infrastructure::persistence::mappers::WebhookMapper;
use async_trait::async_trait;
use dbnexus::sea_orm::{ActiveModelTrait, ColumnTrait, EntityTrait, QueryFilter};
use dbnexus::DbPool;
use std::sync::Arc;

/// Webhook repository implementation
#[derive(Clone)]
pub struct WebhookRepoImpl {
    pool: Arc<DbPool>,
}

impl WebhookRepoImpl {
    /// Create new webhook repository instance
    pub fn new(pool: Arc<DbPool>) -> Self {
        Self { pool }
    }
}

#[async_trait]
impl WebhookRepository for WebhookRepoImpl {
    async fn create(&self, webhook: &Webhook) -> Result<Webhook, RepositoryError> {
        let session = self
            .pool
            .get_session("admin")
            .await
            .map_err(|e| RepositoryError::Database(e.into()))?;

        let entity = WebhookMapper::to_entity(webhook);
        let active_model = webhook::ActiveModel::from(entity);

        active_model
            .insert(
                session
                    .connection()
                    .map_err(|e| RepositoryError::Database(e.into()))?,
            )
            .await
            .map_err(|e| RepositoryError::Database(e.into()))?;

        Ok(webhook.clone())
    }

    async fn find_by_id(
        &self,
        id: crate::domain::id::Id,
    ) -> Result<Option<Webhook>, RepositoryError> {
        let session = self
            .pool
            .get_session("admin")
            .await
            .map_err(|e| RepositoryError::Database(e.into()))?;

        let entity = webhook::Entity::find_by_id(id)
            .one(
                session
                    .connection()
                    .map_err(|e| RepositoryError::Database(e.into()))?,
            )
            .await
            .map_err(|e| RepositoryError::Database(e.into()))?;

        Ok(entity.map(WebhookMapper::to_domain))
    }

    async fn find_by_team_id(
        &self,
        team_id: crate::domain::id::Id,
    ) -> Result<Vec<Webhook>, RepositoryError> {
        let session = self
            .pool
            .get_session("admin")
            .await
            .map_err(|e| RepositoryError::Database(e.into()))?;

        let entities = webhook::Entity::find()
            .filter(webhook::Column::TeamId.eq(team_id))
            .all(
                session
                    .connection()
                    .map_err(|e| RepositoryError::Database(e.into()))?,
            )
            .await
            .map_err(|e| RepositoryError::Database(e.into()))?;

        Ok(WebhookMapper::to_domain_list(entities))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::common::test_helpers::create_test_db_pool;

    fn sample_webhook() -> Webhook {
        Webhook::new(
            crate::domain::id::Id::generate(),
            crate::domain::id::Id::generate(),
            "https://example.com/webhook".to_string(),
        )
    }

    // construction

    #[test]
    fn test_new_creates_repository_instance() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let pool = create_test_db_pool();
        let repo = WebhookRepoImpl::new(pool);
        let _clone = repo.clone();
    }

    #[test]
    fn test_webhook_new_construction_does_not_panic() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let hook = sample_webhook();
        assert!(!hook.url.is_empty());
    }

    // CRUD against real DB

    #[tokio::test]
    async fn test_create_inserts_record() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let repo = WebhookRepoImpl::new(create_test_db_pool());
        let webhook = sample_webhook();
        let result = repo.create(&webhook).await;
        assert!(result.is_ok(), "create failed: {:?}", result.err());

        // Verify DB state: find_by_id should return the created webhook
        let found = repo
            .find_by_id(webhook.id)
            .await
            .expect("find_by_id failed")
            .expect("webhook should exist after create");
        assert_eq!(found.id, webhook.id);
        assert_eq!(found.team_id, webhook.team_id);
        assert_eq!(found.url, webhook.url);

        // Verify find_by_team_id also returns the created webhook
        let by_team = repo
            .find_by_team_id(webhook.team_id)
            .await
            .expect("find_by_team_id failed");
        let matching = by_team.into_iter().find(|w| w.id == webhook.id);
        assert!(
            matching.is_some(),
            "created webhook should be findable by team_id"
        );
    }

    #[tokio::test]
    async fn test_find_by_id_returns_none_for_unknown() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let repo = WebhookRepoImpl::new(create_test_db_pool());
        let result = repo.find_by_id(crate::domain::id::Id::generate()).await;
        assert!(result.is_ok(), "find_by_id failed: {:?}", result.err());
        assert!(result.unwrap().is_none(), "unknown id should return None");
    }

    #[tokio::test]
    async fn test_find_by_team_id_returns_empty_for_unknown() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let repo = WebhookRepoImpl::new(create_test_db_pool());
        let result = repo
            .find_by_team_id(crate::domain::id::Id::generate())
            .await;
        assert!(result.is_ok(), "find_by_team_id failed: {:?}", result.err());
        assert!(
            result.unwrap().is_empty(),
            "unknown team_id should return empty vec"
        );
    }

    // RepositoryError variant display exhaustive

    #[test]
    fn test_repository_error_database_display() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = RepositoryError::Database(anyhow::anyhow!("connection refused"));
        let msg = format!("{}", err);
        assert!(msg.contains("Database error"));
        assert!(msg.contains("connection refused"));
    }

    #[test]
    fn test_repository_error_not_found_display() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let err = RepositoryError::NotFound;
        assert_eq!(format!("{}", err), "Record not found");
    }

    // From<dbnexus::sea_orm::DbErr> exhaustive

    #[test]
    fn test_repository_error_from_dberr_record_not_found() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let db_err = dbnexus::sea_orm::DbErr::RecordNotFound("webhook missing".to_string());
        let repo_err: RepositoryError = db_err.into();
        match repo_err {
            RepositoryError::Database(_) => {}
            other => panic!("expected Database variant, got {:?}", other),
        }
    }

    #[test]
    fn test_repository_error_from_dberr_query_runtime() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let db_err = dbnexus::sea_orm::DbErr::Query(dbnexus::sea_orm::RuntimeErr::Internal(
            "syntax error".to_string(),
        ));
        let repo_err: RepositoryError = db_err.into();
        match repo_err {
            RepositoryError::Database(_) => {}
            other => panic!("expected Database variant, got {:?}", other),
        }
    }

    #[test]
    fn test_repository_error_from_dberr_connection_acquire() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let db_err =
            dbnexus::sea_orm::DbErr::ConnectionAcquire(dbnexus::sea_orm::ConnAcquireErr::Timeout);
        let repo_err: RepositoryError = db_err.into();
        match repo_err {
            RepositoryError::Database(_) => {}
            other => panic!("expected Database variant, got {:?}", other),
        }
    }

    #[test]
    fn test_repository_error_from_dberr_record_not_inserted() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let db_err = dbnexus::sea_orm::DbErr::RecordNotInserted;
        let repo_err: RepositoryError = db_err.into();
        match repo_err {
            RepositoryError::Database(_) => {}
            other => panic!("expected Database variant, got {:?}", other),
        }
    }

    // Production conversion path: dbnexus::DbError -> anyhow -> RepositoryError

    #[test]
    fn test_repository_error_from_dbnexus_db_error_connection_path() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let inner =
            dbnexus::sea_orm::DbErr::ConnectionAcquire(dbnexus::sea_orm::ConnAcquireErr::Timeout);
        let db_err = dbnexus::DbError::Connection(inner);
        let any_err: anyhow::Error = db_err.into();
        let repo_err = RepositoryError::Database(any_err);
        let msg = format!("{}", repo_err);
        assert!(msg.contains("Database error"));
    }

    #[test]
    fn test_repository_error_from_dbnexus_db_error_config_path() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let db_err = dbnexus::DbError::Config("invalid url".to_string());
        let any_err: anyhow::Error = db_err.into();
        let repo_err = RepositoryError::Database(any_err);
        let msg = format!("{}", repo_err);
        assert!(msg.contains("Database error"));
    }

    #[test]
    fn test_repository_error_from_dbnexus_db_error_permission_path() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let db_err = dbnexus::DbError::Permission("forbidden".to_string());
        let any_err: anyhow::Error = db_err.into();
        let repo_err = RepositoryError::Database(any_err);
        let msg = format!("{}", repo_err);
        assert!(msg.contains("Database error"));
    }

    #[test]
    fn test_repository_error_from_dbnexus_db_error_transaction_path() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let db_err = dbnexus::DbError::Transaction("deadlock".to_string());
        let any_err: anyhow::Error = db_err.into();
        let repo_err = RepositoryError::Database(any_err);
        let msg = format!("{}", repo_err);
        assert!(msg.contains("Database error"));
    }

    #[test]
    fn test_repository_error_from_dbnexus_db_error_migration_path() {
        if crate::common::test_helpers::skip_if_no_test_db() {
            return;
        }
        let db_err = dbnexus::DbError::Migration("schema mismatch".to_string());
        let any_err: anyhow::Error = db_err.into();
        let repo_err = RepositoryError::Database(any_err);
        let msg = format!("{}", repo_err);
        assert!(msg.contains("Database error"));
    }
}