backbone-bucket 0.2.1

Bucket Bounded Context: File Storage Module for Backbone Framework
Documentation
//! ContentHash Projector (Event Handler)
//!
//! Generated by backbone-schema. Do not edit manually.
//!
//! This projector listens to domain events and updates the projection.

use std::sync::Arc;

use anyhow::Result;
use async_trait::async_trait;
use chrono::Utc;

use super::ContentHashProjection;
use crate::domain::entity::ContentHash;
use crate::domain::events::{
    ContentHashCreatedEvent, ContentHashUpdatedEvent, ContentHashDeletedEvent,
};

// ============================================================================
// EVENT HANDLER TRAIT
// ============================================================================

/// Trait for handling ContentHash domain events
///
/// All handler methods receive the event sequence number for tracking
/// which events have been processed by the projector.
#[async_trait]
pub trait ContentHashEventHandler: Send + Sync {
    /// Handle entity created event
    async fn on_created(&self, event: ContentHashCreatedEvent, sequence: i64) -> Result<()>;
    /// Handle entity updated event
    async fn on_updated(&self, event: ContentHashUpdatedEvent, sequence: i64) -> Result<()>;
    /// Handle entity deleted event
    async fn on_deleted(&self, event: ContentHashDeletedEvent, sequence: i64) -> Result<()>;
}

// ============================================================================
// PROJECTION REPOSITORY
// ============================================================================

/// Repository for ContentHash projections
#[async_trait]
pub trait ContentHashProjectionRepository: Send + Sync {
    async fn save(&self, projection: &ContentHashProjection) -> Result<()>;
    async fn find_by_id(&self, id: uuid::Uuid) -> Result<Option<ContentHashProjection>>;
    async fn delete(&self, id: uuid::Uuid) -> Result<()>;
    async fn rebuild_all(&self) -> Result<u64>;
}

// ============================================================================
// PROJECTOR
// ============================================================================

/// Projector that updates ContentHash projection from events
pub struct ContentHashProjector<R: ContentHashProjectionRepository> {
    repository: Arc<R>,
}

impl<R: ContentHashProjectionRepository> ContentHashProjector<R> {
    /// Create a new projector
    pub fn new(repository: Arc<R>) -> Self {
        Self { repository }
    }

    /// Rebuild all projections from event history
    pub async fn rebuild(&self) -> Result<u64> {
        self.repository.rebuild_all().await
    }

    /// Process a stored event from the event store
    ///
    /// This method dispatches the event to the appropriate handler based on event type.
    /// Returns Ok(true) if the event was processed, Ok(false) if it was skipped.
    pub async fn process_stored_event(&self, event: &crate::infrastructure::event_store::StoredEvent) -> Result<bool>
    where
        Self: ContentHashEventHandler,
    {
        let sequence = event.sequence;

        match event.event_type.as_str() {
            "ContentHashCreatedEvent" => {
                let created: ContentHashCreatedEvent = serde_json::from_value(event.payload.clone())?;
                self.on_created(created, sequence).await?;
                Ok(true)
            }
            "ContentHashUpdatedEvent" => {
                let updated: ContentHashUpdatedEvent = serde_json::from_value(event.payload.clone())?;
                self.on_updated(updated, sequence).await?;
                Ok(true)
            }
            "ContentHashDeletedEvent" => {
                let deleted: ContentHashDeletedEvent = serde_json::from_value(event.payload.clone())?;
                self.on_deleted(deleted, sequence).await?;
                Ok(true)
            }
            _ => Ok(false), // Event type not handled by this projector
        }
    }
}

#[async_trait]
impl<R: ContentHashProjectionRepository> ContentHashEventHandler for ContentHashProjector<R> {

    async fn on_created(&self, event: ContentHashCreatedEvent, sequence: i64) -> Result<()> {
        let mut projection = ContentHashProjection::new(
            event.id,
            event.hash,
            event.size_bytes,
            event.storage_key,
            event.storage_backend,
            event.reference_count,
            event.first_uploaded_at,
            event.last_referenced_at,
            event.fingerprint,
            event.metadata
        );

        // Track the event sequence for this projection
        projection.apply_event(sequence);

        self.repository.save(&projection).await
    }

    async fn on_updated(&self, event: ContentHashUpdatedEvent, sequence: i64) -> Result<()> {
        if let Some(mut projection) = self.repository.find_by_id(event.id).await? {
            // Apply updates from event
            projection.hash = event.hash;
            projection.size_bytes = event.size_bytes;
            projection.storage_key = event.storage_key;
            projection.storage_backend = event.storage_backend;
            projection.reference_count = event.reference_count;
            projection.first_uploaded_at = event.first_uploaded_at;
            projection.last_referenced_at = event.last_referenced_at;
            projection.fingerprint = event.fingerprint;
            projection.metadata = event.metadata;
            // Track the event sequence for this projection
            projection.apply_event(sequence);

            self.repository.save(&projection).await?;
        }

        Ok(())
    }

    async fn on_deleted(&self, event: ContentHashDeletedEvent, _sequence: i64) -> Result<()> {
        self.repository.delete(event.id).await
    }
}

// ============================================================================
// CUSTOM EVENT HANDLERS
// ============================================================================
// <<< CUSTOM HANDLERS START >>>

// <<< CUSTOM HANDLERS START >>>
// Add custom event handlers here
// <<< CUSTOM HANDLERS END >>>