rostra-client-db 0.1.2

Embedded database and projections for a Rostra client
Documentation
//! Event-related database record types.
//!
//! Events in Rostra form a DAG (Directed Acyclic Graph) where each event
//! references parent events. The event "envelope" (metadata + signature) is
//! stored separately from the event "content" (payload) to allow content
//! pruning while maintaining DAG integrity.

use std::borrow::Cow;

use bincode::{Decode, Encode};
use rostra_core::event::{EventContentRaw, EventContentUnsized, EventExt, SignedEvent};
use rostra_core::{ExternalEventId, ShortEventId, Timestamp};
use serde::Serialize;

/// Record for the main `events` table.
///
/// Contains the signed event envelope (metadata + signature). The actual
/// content is stored separately in `content_store`.
#[derive(Debug, Encode, Decode, Clone, Serialize)]
pub struct EventRecord {
    /// The signed event (includes event metadata and cryptographic signature)
    pub signed: SignedEvent,
}

impl EventExt for EventRecord {
    fn event(&self) -> &rostra_core::event::Event {
        self.signed.event()
    }
}

/// Record for the `events_missing` table.
///
/// When we receive an event that references a parent we don't have, we create
/// a "missing" record for that parent. This drives sync to fetch the missing
/// event.
#[derive(Decode, Encode, Debug)]
pub struct EventsMissingRecord {
    /// If set, a content deletion event was received before the actual event.
    ///
    /// When the missing event is finally received, its content should be
    /// marked as deleted immediately rather than processed normally.
    ///
    /// Multiple direct deleters are merged by maximum
    /// `(event.timestamp, ShortEventId)`. An ordinary child cannot erase
    /// existing deletion attribution.
    pub deleted_by: Option<ShortEventId>,
}

/// Marker record for the `events_heads` table.
///
/// The key `(author, event_id)` identifies the head; this empty struct just
/// marks its existence. A "head" is an event with no known children - the
/// current tip of the DAG for that author.
#[derive(Decode, Encode, Debug)]
pub struct EventsHeadsTableRecord;

/// Authoritative value retained for a social-vote singleton winner.
#[derive(Debug, Encode, Decode, Clone, Copy, PartialEq, Eq, Serialize)]
pub enum SocialVoteValue {
    /// A vote against the target.
    Down,
    /// No vote for or against the target.
    Neutral,
    /// A vote for the target.
    Up,
}

impl SocialVoteValue {
    /// Return the vote's contribution to the target's aggregate.
    pub fn score(self) -> i64 {
        match self {
            Self::Down => -1,
            Self::Neutral => 0,
            Self::Up => 1,
        }
    }

    /// Return the public optional-boolean representation.
    pub fn as_upvote(self) -> Option<bool> {
        match self {
            Self::Down => Some(false),
            Self::Neutral => None,
            Self::Up => Some(true),
        }
    }
}

impl From<Option<bool>> for SocialVoteValue {
    fn from(upvote: Option<bool>) -> Self {
        match upvote {
            Some(false) => Self::Down,
            None => Self::Neutral,
            Some(true) => Self::Up,
        }
    }
}

/// Authoritative current projection retained for a social-vote winner.
#[derive(Debug, Encode, Decode, Clone, Copy, PartialEq, Eq, Serialize)]
pub struct SocialVoteProjection {
    /// Full post identity needed to disambiguate equal shortened event IDs.
    pub target: ExternalEventId,
    /// Winner's contribution to the target aggregate.
    pub value: SocialVoteValue,
}

/// Record for singleton event tables (`events_singletons`,
/// `events_singletons_new`).
///
/// All singleton records retain their source ID for deterministic ordering and
/// attribution. Social-vote records also retain their authoritative current
/// full-target/value projection so incremental updates do not depend on
/// GC-eligible source content.
#[derive(Debug, Encode, Decode, Clone, Serialize)]
pub struct EventSingletonRecord {
    /// The event ID of the latest singleton event.
    pub event_id: ShortEventId,
    /// Current vote projection for a well-shaped vote; absent for other kinds.
    ///
    /// Every retained `SOCIAL_VOTE` winner must contain `Some`, and every other
    /// singleton kind must contain `None`; either opposite is corruption. A
    /// retained target's shortened event ID must also equal its row auxiliary
    /// key.
    pub social_vote: Option<SocialVoteProjection>,
}

impl super::LatestEventValue for EventSingletonRecord {
    fn event_id(&self) -> ShortEventId {
        self.event_id
    }
}

// ============================================================================
// Content Deduplication Types (V1)
//
// These types support storing content by hash for deduplication across events.
// ============================================================================

/// Content stored in the `content_store` table, keyed by ContentHash.
///
/// This enables content deduplication - identical content (e.g., the same
/// image posted by multiple users) is stored only once.
#[derive(Debug, Encode, Decode, Clone, Serialize)]
pub struct ContentStoreRecord<'a>(pub Cow<'a, EventContentUnsized>);

/// Owned record for the `content_store` table.
pub type ContentStoreRecordOwned = ContentStoreRecord<'static>;

/// Per-event content processing state stored in `events_content_state` table.
///
/// This enum tracks the content processing lifecycle for each event:
///
/// ## State Transitions
///
/// ```text
/// Event inserted ──► Missing ──► (no entry) ──► Deleted/Pruned
///                       │             │
///                       │             └─ Content processed successfully
///                       │                (side effects applied)
///                       │
///                       ├─ Can also go directly to Deleted/Pruned
///                       │
///                       └─► Invalid ──► Deleted
/// ```
///
/// Note: Events with `content_len == 0` skip the `Missing` state entirely. They
/// go straight to "no entry" (processed) unless they start in `Deleted`.
///
/// ## Interpretation
///
/// - **No entry in table**: Content has been processed for this event. This is
///   the normal state after successful content processing. Side effects (reply
///   counts, follow updates, etc.) have been applied. Also the state for events
///   with no content (`content_len == 0`) unless they start in `Deleted`.
///
/// - **`Missing`**: Event was inserted but content hasn't been received or
///   processed yet. The event's content side effects have NOT been applied.
///
/// - **`Invalid`**: Content was received but failed validation (e.g. CBOR
///   deserialization). RC has been decremented. Content bytes are discarded.
///
/// - **`Deleted` / `Pruned`**: Content is unwanted. RC has been decremented. An
///   eligible Deleted social-post edit may still contribute immutable
///   replacement metadata without ordinary content processing.
///
/// ## Idempotency Guarantee
///
/// The `Missing` state ensures content processing is idempotent:
/// - `process_event_content_tx` checks for `Missing` before processing
/// - If `Missing` → process content, then remove the marker
/// - If no entry → skip (already processed)
/// - If `Deleted`/`Pruned`/`Invalid` → skip ordinary processing; the narrow
///   Deleted social-post lineage exception remains idempotent table insertion
///
/// This prevents duplicate side effects (e.g., incrementing reply_count twice)
/// when the same content is received multiple times for the same event.
#[derive(Debug, Encode, Decode, Clone, Copy, Serialize, PartialEq, Eq)]
pub enum EventContentState {
    /// Content has not been received/processed yet for this event.
    ///
    /// This state is set when an event with `content_len > 0` is inserted
    /// (in `insert_event_tx`). Events with `content_len == 0` skip this state,
    /// going directly to processed or `Deleted`.
    ///
    /// When `process_event_content_tx` runs and sees this state:
    /// 1. It processes the content (applies side effects)
    /// 2. Stores content in `content_store` if not already there
    /// 3. Removes this `Missing` marker (deletes entry from table)
    ///
    /// After processing, the event will have NO entry in
    /// `events_content_state`, indicating content was successfully
    /// processed.
    ///
    /// When the event has a current `events_content_missing` row, the
    /// `next_fetch_attempt` field mirrors the `Timestamp` component of that
    /// canonical at-most-one `(Timestamp, ShortEventId)` key, enabling removal
    /// from the table (which requires the full composite key).
    Missing {
        /// When we last attempted to fetch this content from peers.
        last_fetch_attempt: Option<Timestamp>,
        /// Number of times we've attempted to fetch this content.
        fetch_attempt_count: u16,
        /// Scheduled time for next fetch attempt.
        next_fetch_attempt: Timestamp,
    },

    /// Content was deleted by the author via a deletion event.
    ///
    /// When a deletion event targets this event's content:
    /// - This state is set with a reference to the deleting event
    /// - RC is decremented in `content_rc`
    /// - Content may be garbage collected if RC reaches 0
    Deleted {
        /// Canonical direct deleter: maximum
        /// `(event.timestamp, ShortEventId)`.
        deleted_by: ShortEventId,
    },

    /// Content was pruned locally (e.g., too large to store).
    ///
    /// Unlike `Deleted`, this is a local decision, not an author request.
    /// Used when content exceeds size limits or for storage management.
    Pruned,

    /// Content was received but failed validation.
    ///
    /// The content bytes could not be deserialized for the event's kind.
    /// RC has been decremented and content bytes are not stored.
    /// A later author deletion can supersede this with `Deleted` without
    /// another RC decrement.
    Invalid,
}

/// Result of looking up event content.
///
/// This is returned by `get_event_content_full_tx` and combines the per-event
/// state with the actual content from the content store.
#[derive(Debug, Clone)]
pub enum EventContentResult {
    /// Content is present and valid
    Present(EventContentRaw),
    /// Content was received but failed validation
    Invalid,
    /// Content was deleted by the author
    Deleted {
        /// The event that requested this content be deleted
        deleted_by: ShortEventId,
    },
    /// Content was pruned locally
    Pruned,
    /// Content is not in the store (check events_content_missing)
    Missing,
}

impl EventContentResult {
    /// Returns the content if present and valid.
    pub fn content(&self) -> Option<&EventContentRaw> {
        match self {
            EventContentResult::Present(c) => Some(c),
            _ => None,
        }
    }

    /// Returns true if content is present and valid.
    pub fn is_present(&self) -> bool {
        matches!(self, EventContentResult::Present(_))
    }

    /// Returns true if content was deleted.
    pub fn is_deleted(&self) -> bool {
        matches!(self, EventContentResult::Deleted { .. })
    }
}

// ============================================================================
// Event Reception Tracking (V6)
//
// These types track when and how we received each event.
// ============================================================================

use rostra_core::event::IrohNodeId;
use rostra_core::id::RostraId;

/// How we acquired an event.
///
/// Tracks the source and method by which we received an event, useful for
/// debugging sync issues, understanding network propagation, and analytics.
#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, Serialize)]
pub enum EventReceivedSource {
    /// Event was backfilled during a database migration.
    ///
    /// For events that existed before we started tracking reception info.
    Migration,

    /// Event was pushed to us by a peer.
    Pushed {
        /// The identity that sent us this event (if known).
        from_id: Option<RostraId>,
        /// The iroh node that sent us this event (if known).
        from_node: Option<IrohNodeId>,
    },

    /// We actively pulled/requested this event.
    Pulled {
        /// The identity we pulled from (if known).
        from_id: Option<RostraId>,
        /// The iroh node we pulled from (if known).
        from_node: Option<IrohNodeId>,
        /// Description of the task/query that triggered this pull.
        task: Option<String>,
    },

    /// Event was created locally by this node.
    Local,
}

/// Information about when and how we received an event.
///
/// Stored in the `events_received_at` table, keyed by `(Timestamp,
/// reception_order)`.
///
/// The key `(Timestamp, u64)` is allocated durably from the database-local
/// reception sequence. Insertion fails without replacement if the key is
/// occupied. The event ID is stored in the value for lookup.
#[derive(Debug, Encode, Decode, Clone, Serialize)]
pub struct EventReceivedRecord {
    /// The event that was received.
    pub event_id: ShortEventId,
    /// How we acquired this event.
    pub source: EventReceivedSource,
}